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

}

}

相关推荐
老前端的功夫18 小时前
【Java从入门到入土】06:String的72变:从字符串拼接到底层优化
java·开发语言
又是忙碌的一天18 小时前
Java 面向对象三大特性:封装、继承、多态深度解析
java·前端·python
彭于晏Yan19 小时前
Springboot实现连接多个ElasticSearch数据库
数据库·spring boot·elasticsearch
隔壁小邓19 小时前
在Java中实现优雅的CQRS架构
java·开发语言·架构
河边小咸鱼19 小时前
pdd校招实习生内推【实时更新链接】2027届实习、2026届春招
java·c++·golang
只能是遇见19 小时前
【SpringBoot3】Spring Boot 3.0 集成 Mybatis Plus
spring boot·后端·mybatis
zzb158019 小时前
Agent学习-Reflection框架
java·人工智能·python·学习·ai
Holen&&Beer19 小时前
Spring-Profile与部署说明
java·后端·spring
棉花糖超人19 小时前
【操作系统】三、线程
java·开发语言·操作系统
liuyao_xianhui19 小时前
优选算法_判断字符是否唯一_C++
java·开发语言·数据结构·c++·算法·链表