springboot上传下载文件

@RequestMapping("bigJson")

@RestController

@Slf4j

public class TestBigJsonController {

复制代码
@Resource
private BigjsonService bigjsonService;

@PostMapping("uploadJsonFile")
public ResponseResult<Long> uploadJsonFile(@RequestParam("file")MultipartFile file){
    if (file.isEmpty()) {
        return ResponseResult.error();
    }

    try {
        Bigjson bigjson = new Bigjson();
        bigjson.setJsonFileName(file.getName());

        // 解析JSON文件
        ObjectMapper objectMapper = new ObjectMapper();
        JSONObject jsonObject = objectMapper.readValue(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8), JSONObject.class);
        bigjson.setJsonFile(jsonObject.toJSONString());

        //
        Long id = bigjsonService.uploadJsonFile(bigjson);

        // 返回成功响应
        return ResponseResult.success(id);
    } catch (IOException e) {
        log.error("上传错误");
        return ResponseResult.error();
    }
}

@GetMapping("/downloadJson")
public ResponseEntity<byte[]> downloadJson(@RequestParam("id") Long id){
    Bigjson bigjson = bigjsonService.getById(id);
    byte[] bytes = bigjson.getJsonFile().getBytes();

    // 设置响应头
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+bigjson.getJsonFileName()+".json");
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");

    // 返回响应
    return new ResponseEntity<>(bytes, headers, HttpStatus.OK);

}

}

相关推荐
2301_793086876 分钟前
SpringCloud 02 服务治理 Nacos
java·spring boot·spring cloud
小七rrrrr17 分钟前
动态规划法 - 53. 最大子数组和
java·算法·动态规划
自由的疯26 分钟前
在 Java IDEA 中使用 DeepSeek 详解
java·后端·架构
自由的疯32 分钟前
Java 通过接口方式使用 DeepSeek 详解
java·后端·trae
敲代码中40 分钟前
Maven入门到精通
java·maven
拂晓银砾1 小时前
Java数据结构-队列
java·数据结构
重生成为编程大王1 小时前
Java ConcurrentHashMap 深度解析
java·开发语言
阿华的代码王国1 小时前
【Android】适配器与外部事件的交互
android·xml·java·前端·后端·交互
MacroZheng1 小时前
还在用WebSocket实现即时通讯?试试MQTT吧,真香!
java·spring boot·后端