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

}

}

相关推荐
大飞哥~BigFei2 小时前
RabbitMq消费延迟衰减重试实现思路
java·分布式·rabbitmq
有趣的野鸭2 小时前
JAVA课程十一次实验课程主要知识点示例
java·前端·数据库
q***07144 小时前
Spring Boot 多数据源解决方案:dynamic-datasource-spring-boot-starter 的奥秘(上)
java·spring boot·后端
郝开4 小时前
Spring Boot 2.7.18(最终 2.x 系列版本)8 - 日志:Log4j2 基本概念;Log4j2 多环境日志配置策略
spring boot·单元测试·log4j
q***49864 小时前
Spring Boot 3.4 正式发布,结构化日志!
java·spring boot·后端
不会吃萝卜的兔子6 小时前
spring - 微服务授权 2 实战
spring·oauth2·authorization
沐浴露z6 小时前
【微服务】基本概念介绍
java·微服务
Z3r4y7 小时前
【代码审计】RuoYi-4.7.3&4.7.8 定时任务RCE 漏洞分析
java·web安全·ruoyi·代码审计
Kuo-Teng8 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展