spring-boot 实现文件上传下载

@Controller
public class FileUploadCtrl {
    @Value("${file.upload.dir}")
    private String path;

    /**
     * 实现文件上传
     * */
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> fileUpload(@RequestParam("fileName") MultipartFile file){
        Map<String,Object> map = new HashMap<String, Object>();
        int no = 0;
        String msg = "上传失败!";

        if(!file.isEmpty()){
            String fileName = file.getOriginalFilename();

            File dest = new File(path + "/" + fileName);

            if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                dest.getParentFile().mkdir();
            }

            try {
                file.transferTo(dest); //保存文件
                no = 1;
                msg = "上传成功!";
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        map.put("no",no);
        map.put("msg", msg);

        return map;
    }


    @RequestMapping(
            value = "/fileDownload",
            method = RequestMethod.GET
    )
    public ResponseEntity<?> getGwFileContent(@RequestParam String fileName,@RequestParam int flag) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        String filepath = path+"/"+fileName;;

        InputStream is = null;

        try {
            headers.add("Content-Disposition", String.format("attachment; filename="%s"", new String(fileName.getBytes("GBK"), "ISO8859-1")));

            if(flag==0){//表示获取缩略图
                File file = new File(filepath);

                filepath = path+"/xx"+fileName;
                File xxFile = new File(filepath);
                if(!xxFile.exists()){//不存在就生成缩略图
                    Thumbnails.of(file).scale(0.25f).toFile(xxFile);
                }
            }

            is = new FileInputStream(new File(filepath));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(is));
    }

}
原文地址:https://www.cnblogs.com/yshyee/p/7839101.html