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

}

}

相关推荐
似水明俊德几秒前
01-C#.Net-泛型-学习笔记
java·笔记·学习·c#·.net
百锦再几秒前
飞算 JavaAI:我的编程强力助推引擎
java·spring·ai·编程·idea·code·飞算
wuyaolong00733 分钟前
Spring Boot 3.4 正式发布,结构化日志!
java·spring boot·后端
hua8722240 分钟前
Golang 构建学习
java·开发语言·学习
Halo_tjn1 小时前
Java 三个修饰符 相关知识点
java·开发语言
毕设源码-朱学姐1 小时前
【开题答辩全过程】以 广东省非遗文化信息管理系统的设计与实现为例,包含答辩的问题和答案
java
番茄去哪了1 小时前
Java基础面试题day01
java·开发语言·后端·javase·八股·面向对象编程
遇事不决问清风1 小时前
AI 驱动开发实战复盘:从 0 到上线,一个真实项目的工程化总结
java·ai编程
wuqingshun3141591 小时前
说说进程和线程的区别?
java·开发语言·jvm
Memory_荒年2 小时前
自定义 Spring Boot Starter:手搓“轮子”,但要搓出兰博基尼!
java·后端