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

}

}

相关推荐
总爱写点小BUG5 分钟前
打印不同的三角形(C语言)
java·c语言·算法
星辰烈龙32 分钟前
黑马程序员Java基础9
java·开发语言
山沐与山33 分钟前
【Redis】Redis集群模式架构详解
java·redis·架构
ss27344 分钟前
Java并发编程:DelayQueue延迟订单系统
java·python·算法
wcy_10111 小时前
七大软件设计原则
java·设计规范
invicinble1 小时前
jar包在执行的时候需要关注的细节(提供一个解构jvm问题的视角)
java·jvm·jar
麦芽糖02191 小时前
SSE介绍及使用(Server-Send Events)
java
alan07211 小时前
【Java + Elasticsearch全量 & 增量同步实战】
java·elasticsearch·jenkins
Rover.x1 小时前
Netty基于SpringBoot实现WebSocket
spring boot·后端·websocket
hashiqimiya1 小时前
后端springboot的接收前端发来的数据反序列化原理
java