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

}

}

相关推荐
FIavor.10 分钟前
怎么办这是Apifox里执行http://localhost:9002/goods/getByUserName?name=“张三“为什么我改了还是500?
java·网络·网络协议·http
编程饭碗11 分钟前
【Java集合】
java
岁岁岁平安12 分钟前
Java的双重检查锁机制(DCL)与懒加载的单例模式
java·单例模式·synchronized·
Jabes.yang19 分钟前
Java面试场景:从Spring Boot到Kubernetes的技术问答
java· 面试· spring boot· 微服务· kubernetes· 技术栈· redis
小咕聊编程31 分钟前
【含文档+PPT+源码】基于SpringBoot+Gpt个人健康管理系统
java·gpt·tomcat·毕业设计·hibernate
阿无,42 分钟前
Java设计模式之工厂模式
java·开发语言·设计模式
哎呀呦呵1 小时前
python内置模块-re模块介绍使用
java·python·mysql
louisgeek1 小时前
Java CompletableFuture
java
ะัี潪ิื1 小时前
精灵图(雪碧图)的生成和使用
java·css
web安全工具库1 小时前
从课堂笔记到实践:深入理解Linux C函数库的奥秘
java·数据库·算法