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

}

}

相关推荐
陈平安Java and C4 小时前
MyBatisPlus
java
秋野酱5 小时前
如何在 Spring Boot 中实现自定义属性
java·数据库·spring boot
安的列斯凯奇5 小时前
SpringBoot篇 单元测试 理论篇
spring boot·后端·单元测试
Bunny02125 小时前
SpringMVC笔记
java·redis·笔记
blammmp5 小时前
Java EE 进阶:Spring MVC(1)
spring·java-ee·mvc
feng_blog66886 小时前
【docker-1】快速入门docker
java·docker·eureka
枫叶落雨2227 小时前
04JavaWeb——Maven-SpringBootWeb入门
java·maven
m0_748232397 小时前
SpringMVC新版本踩坑[已解决]
java
多则惑少则明7 小时前
SSM开发(一)JAVA,javaEE,spring,springmvc,springboot,SSM,SSH等几个概念区别
spring boot·spring·ssh
码农小灰7 小时前
Spring MVC中HandlerInterceptor和Filter的区别
java·spring·mvc