spring 上傳文件和下載文件

1. 上傳文件

  • 借助multipart形式可以比較輕松的上傳文件
  • 代碼實(shí)現(xiàn)
    可以使用MultipartFile和Part兩種方法去操作上傳的文件

MultipartFile的兩個(gè)實(shí)現(xiàn)類(ctrl+alt+b)
1.CommonsMultipartFile(非servlet3.0以上的服務(wù))
2.StandardMultipartFile


MultipartFile.java

Part實(shí)現(xiàn)類ApplicationPart(一般使用注解@RequestPart("xxx)Part xxx)
多了一個(gè)delete的方法


part.java
  • 使用配置
@Configuration
public class MultipartConfig {
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //  單個(gè)數(shù)據(jù)大小
        factory.setMaxFileSize(DataSize.parse("102400KB"));
        /// 總上傳數(shù)據(jù)大小
        factory.setMaxRequestSize(DataSize.parse("102400KB"));
        //設(shè)置文件路徑
        factory.setLocation("/app/temp/");
        //默認(rèn)值是0 ,就是不管文件大小,都會(huì)將文件保存到磁盤(pán)中
        //factory.setFileSizeThreshold(DataSize.parse("0B"));
        return factory.createMultipartConfig();
    }
}
  • 上傳單文件到指定路徑中 這種可以自己指定文件的保存路徑,配置中factory.setLocation("/app/temp/");這句代碼不需要
 @RequestMapping("/uploadFile")
    public Object uploadFile(@RequestParam("file") MultipartFile file,
                             @Validated @Size(min = 3, max = 50, message = "文件描述長(zhǎng)度不符合規(guī)范") @RequestParam("description") String description) throws IOException {
        if (file.isEmpty()) {
            return "文件為空,請(qǐng)重新上傳";
        }

        String realPath1 = ResourceUtils.getURL("classpath:").getPath();
        String filePath = realPath1 + "/images/" + file.getOriginalFilename();
        File dest = new File(filePath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
       }
        file.transferTo(dest);
        return "保存成功";
    }
  • 上傳到服務(wù)的臨時(shí)目錄中
  1. 如果配置了factory.setLocation("/app/temp/");這句話,文件的保存路徑會(huì)為
    C:\Users\lrh\AppData\Local\Temp\tomcat.5166651053557888915.8080\work\Tomcat\localhost\ROOT\app\temp\微信圖片_20190630233947.jpg

2.如果不配置,會(huì)保存在服務(wù)器運(yùn)行時(shí)的一個(gè)臨時(shí)文件夾中,這種相對(duì)比較簡(jiǎn)單
C:\Users\lrh\AppData\Local\Temp\tomcat.245320015338601087.8080\work\Tomcat\localhost\ROOT\微信圖片_20190630233947.jpg

 @RequestMapping("/uploadFile")
    public Object uploadFile(@RequestParam("file") MultipartFile file,
                             @Validated @Size(min = 3, max = 50, message = "文件描述長(zhǎng)度不符合規(guī)范") @RequestParam("description") String description) throws IOException {
        if (file.isEmpty()) {
            return "文件為空,請(qǐng)重新上傳";
        }
        File dest = new File(file.getOriginalFilename());
        file.transferTo(dest);
        return "保存成功";
    }
  • 上傳多個(gè)文件,不同點(diǎn)在于參數(shù)時(shí)數(shù)組,其他一樣
 @RequestMapping("/uploadFiles")
    public Object uploadFile(@RequestParam("files") MultipartFile[] files,
                             @Validated @Size(min = 3, max = 50, message = "文件描述長(zhǎng)度不符合規(guī)范") @RequestParam("description") String description) throws IOException {
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                return "文件為空,請(qǐng)重新上傳";
            }
            File dest = new File(file.getOriginalFilename());
            file.transferTo(dest);
        }
        return "保存成功";
    }
  • 為什么可以不設(shè)置文件的保存文件夾
    因?yàn)槲募诒4娴臅r(shí)候會(huì)先判斷,是否有絕對(duì)路徑file.isAbsolute(),如果沒(méi)有絕對(duì)路徑,就會(huì)從MultipartConfigElement中的Location中獲取路徑,這個(gè)路徑一般時(shí)服務(wù)在運(yùn)行時(shí)的一個(gè)路徑
StandardMultipartFile.java
@Override
        public void transferTo(File dest) throws IOException, IllegalStateException {
            this.part.write(dest.getPath());
            if (dest.isAbsolute() && !dest.exists()) {
                // Servlet 3.0 Part.write is not guaranteed to support absolute file paths:
                // may translate the given path to a relative location within a temp dir
                // (e.g. on Jetty whereas Tomcat and Undertow detect absolute paths).
                // At least we offloaded the file from memory storage; it'll get deleted
                // from the temp dir eventually in any case. And for our user's purposes,
                // we can manually copy it to the requested location as a fallback.
                FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest.toPath()));
            }
        }

ApplicationPart.java
 @Override
    public void write(String fileName) throws IOException {
        File file = new File(fileName);
        if (!file.isAbsolute()) {
            file = new File(location, fileName);
        }
        try {
            fileItem.write(file);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

2. 下載文件

下載文件時(shí)需要設(shè)置響應(yīng)的header

 @RequestMapping("/downLoadImage")
    public Object downLoadImage(@Validated @NotEmpty String fileName, HttpServletResponse response) throws FileNotFoundException {

        String fileRealPath = ResourceUtils.getURL("classpath:").getPath() + "/images/" + fileName;
        File file = new File(fileRealPath);
        if (!file.exists()) {
            return "文件不存在";
        }
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            while (bis.read(buff) != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
            }
        } catch (FileNotFoundException e1) {
            return "系統(tǒng)找不到指定的文件";
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "success";
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容