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

}

}

相关推荐
Apex Predator2 分钟前
windows安装maven环境
java·maven
Bug退退退12310 分钟前
RabbitMQ 工作模式
java·分布式·rabbitmq
华子w90892585935 分钟前
基于 SpringBoot+Vue.js+ElementUI 的 “花开富贵“ 花园管理系统设计与实现7000字论文
vue.js·spring boot·elementui
小时候的阳光1 小时前
SpringBoot3 spring.factories 自动配置功能不生效?
spring boot·spring·失效·factories·imports
小莫分享1 小时前
github 镜像节点
java
链上Sniper2 小时前
智能合约状态快照技术:实现 EVM 状态的快速同步与回滚
java·大数据·linux·运维·web3·区块链·智能合约
大只鹅2 小时前
Springboot3整合ehcache3缓存--XML配置和编程式配置
spring boot·缓存
缘来是庄2 小时前
设计模式之建造者模式
java·设计模式·建造者模式
小湘西2 小时前
Apache HttpClient 的请求模型和 I/O 类型
java·http·apache
沃夫上校3 小时前
Feign调Post接口异常:Incomplete output stream
java·后端·微服务