美文网首页
springBoot 优雅上传下载

springBoot 优雅上传下载

作者: wanggs | 来源:发表于2020-06-06 15:34 被阅读0次
    @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();
        }
    

    相关文章

      网友评论

          本文标题:springBoot 优雅上传下载

          本文链接:https://www.haomeiwen.com/subject/rpygzhtx.html