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