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);

}

}

相关推荐
逸狼13 分钟前
【JavaEE进阶】Spring DI
java·开发语言
m0_7482486513 分钟前
SpringBoot整合easy-es
spring boot·后端·elasticsearch
yonuyeung16 分钟前
代码随想录算法【Day54】
java·数据结构·算法
敲上瘾22 分钟前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
my_styles42 分钟前
2025-alibaba-Sentinel组件
java·开发语言·sentinel
Dongwoo Jeong43 分钟前
类型系统下的语言分类与类型系统基础
java·笔记·python·lisp·fortran·type
肖帆咪1 小时前
deepseek自动化代码生成
java·ai·自动化·ai编程·deepseek
web150854159351 小时前
超级详细Spring AI运用Ollama大模型
人工智能·windows·spring
刘小炮吖i1 小时前
Java 集合:单列集合和双列集合的深度剖析
java·集合