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

}

}

相关推荐
J_liaty26 分钟前
SpringBoot + EMQX:打造物联网设备数据双向通讯的完整解决方案
spring boot·物联网·emqx
kk哥889938 分钟前
分享一些学习JavaSE的经验和技巧
java·开发语言
栈与堆1 小时前
LeetCode 21 - 合并两个有序链表
java·数据结构·python·算法·leetcode·链表·rust
lagrahhn1 小时前
Java的RoundingMode舍入模式
java·开发语言·金融
鸽鸽程序猿1 小时前
【JavaEE】【SpringCloud】注册中心_nacos
java·spring cloud·java-ee
云上凯歌1 小时前
01 GB28181协议基础理解
java·开发语言
Coder_Boy_2 小时前
基于SpringAI的在线考试系统-考试系统DDD(领域驱动设计)实现步骤详解
java·数据库·人工智能·spring boot
毕设源码-钟学长2 小时前
【开题答辩全过程】以 基于Java的运动器材销售网站为例,包含答辩的问题和答案
java·开发语言
workflower2 小时前
软件需求规约的质量属性
java·开发语言·数据库·测试用例·需求分析·结对编程
TracyCoder1232 小时前
Java String:从内存模型到不可变设计
java·算法·string