springBoot 优雅上传下载

2020-06-06  本文已影响0人  wanggs
@RestController
@RequestMapping("file")
@Slf4j
public class FileController {

    private String uploadFilePath = "D:/upload";

    @RequestMapping("/upload")
    public String httpUpload(@RequestParam("files") MultipartFile files[]) {
        JSONObject object = new JSONObject();
        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getOriginalFilename();  // 文件名
            File dest = new File(uploadFilePath + '/' + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                files[i].transferTo(dest);
            } catch (Exception e) {
                log.error("{}", e);
                object.put("success", 2);
                object.put("result", "程序错误,请重新上传");
                return object.toString();
            }
        }
        object.put("success", 1);
        object.put("result", "文件上传成功");
        return object.toString();
    }

    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile() throws FileNotFoundException {
        File file = new File("D:/upload/1.jpg");
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentLength(file.length());
        httpHeaders.setContentDispositionFormData("attachment", "照片.jpg");

        InputStreamResource inputStreamResource = new InputStreamResource(new FileInputStream(file));

        return new ResponseEntity<InputStreamResource>(inputStreamResource, httpHeaders, HttpStatus.OK);
    }


    @GetMapping("/download/zip")
    public void downloadZipFile(HttpServletResponse response) throws IOException {
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
        response.setHeader("Content-Disposition", "attachment; filename=\"images.zip\"");
        List<String> fileNames = Arrays.asList("1.jpg", "2.jpg", "3.jpg");
        ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());

        for (String fileName : fileNames) {
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipOutputStream.putNextEntry(zipEntry);
            FileInputStream inputStream = new FileInputStream("D:/upload/" + fileName);
            IoUtil.copy(inputStream, zipOutputStream);
            inputStream.close();
        }

        zipOutputStream.closeEntry();
        zipOutputStream.close();
    }
上一篇下一篇

猜你喜欢

热点阅读