天天看點

從.Net到Java學習第十篇——Spring Boot檔案上傳和下載下傳

從.Net到Java學習系列目錄

圖檔上傳

Spring Boot中的檔案上傳就是Spring MVC中的檔案上傳,将其內建進來了。

在模闆目錄建立一個新的頁面 profile/uploadPage.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<h2 class="indigo-text center">Upload</h2>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data" class="col m8 s12 offset-m2">
    <div class="input-field col s6">
        <input type="file" id="file" name="file"/>
    </div>
    <div class="col s6 center">
        <button class="btn indigo waves-effect waves-light"
                type="submit" name="save" >Submit
            <i class="mdi-content-send right"></i>
        </button>
    </div>
    <div class="col s12 center red-text" th:text="${error}" th:if="${error}">
        Error during upload
    </div>
    <div class="col m8 s12 offset-m2">
        <img th:src="@{${picturePath}}" width="100" height="100"/>
    </div>
</form>
</body>
</html>      

除了表單中的 enctype 屬性以外,并沒有太多值得關注的。檔案将會通過 POST 方法發送到 upload URL 上,建立控制器PictureUploadController

@Controller
@SessionAttributes("picturePath")
public class PictureUploadController {
    //跳轉到上傳檔案的頁面
    @RequestMapping("upload")
    public String uploadPage() {
        return "profile/uploadPage";
    }
    //處理檔案上傳
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String onUpload(MultipartFile file, HttpServletRequest request, RedirectAttributes redirectAttrs, Model model) throws IOException {
        if (file.isEmpty() || !isImage(file)) {
            redirectAttrs.addFlashAttribute("error", "Incorrect file.Please upload a picture.");
            return "redirect:/upload";
        }
        String filePath =  request.getSession().getServletContext().getRealPath("pictures/");
        Resource picturePath = copyFileToPictures(file,filePath);
        String _path="/pictures/"+picturePath.getFilename();
        model.addAttribute("picturePath",_path);
        return "profile/uploadPage";
    }

    private Resource copyFileToPictures(MultipartFile file,String filePath) throws IOException {
        String filename = file.getOriginalFilename();
        File tempFile = File.createTempFile("pic",
                getFileExtension(filename),  new FileSystemResource(filePath).getFile());
        try (InputStream in = file.getInputStream();
             OutputStream out = new FileOutputStream(tempFile)) {
            IOUtils.copy(in, out);
        }
        return new FileSystemResource(tempFile);
    }

    //判斷上傳檔案的類型是否是圖檔
    private boolean isImage(MultipartFile file) {
        return file.getContentType().startsWith("image");
    }
    //擷取上傳檔案的擴充名
    private static String getFileExtension(String name) {
        return name.substring(name.lastIndexOf("."));
    }
}      

在項目的根目錄下建立 pictures 目錄 ,上述代碼做的第一件事情是在 pictures 目錄下建立一個臨時檔案,這個目錄位于項目的根檔案夾下,是以要確定該目錄是存在的。在 Java 中,臨時檔案隻是用來擷取檔案系統中唯一的檔案辨別符的,使用者可以自行決定是否要删除它 。使用者送出的檔案将會以 MultipartFile 接口的形式注入到控制器中,這個接口提供了多個方法,用來擷取檔案的名稱、大小及其内容 。try...with 代碼塊将會自動關閉流,即便出現異常也會如此,進而移除了finally 這樣的樣闆式代碼 。我們還可以定義上傳檔案的功能。

  • multipart.maxFileSize:這定義了所允許上傳檔案的最大容量。嘗試上傳更大的檔案将會出現 MultipartException,其預設值是 1Mb;
  • multipart.maxRequestSize:這定義了整個 multipart 請求的最大容量,預設值是 10MB。
從.Net到Java學習第十篇——Spring Boot檔案上傳和下載下傳

運作預覽:

從.Net到Java學習第十篇——Spring Boot檔案上傳和下載下傳

圖檔下載下傳

修改控制器PictureUploadController,添加如下代碼:

//圖檔下載下傳
    @RequestMapping(value = "/DownloadPic", method = RequestMethod.GET)
    public void Download(HttpServletRequest req,HttpServletResponse res) {
        String fileName = "pic2456280610589533697.jpg";
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            String filePath =  req.getSession().getServletContext().getRealPath("pictures/");
            bis = new BufferedInputStream(new FileInputStream(new File(filePath + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
    }      

修改uploadPage.html,添加:

<a href="/DownloadPic">下載下傳圖檔</a>      
從.Net到Java學習第十篇——Spring Boot檔案上傳和下載下傳
部落格位址: http://www.cnblogs.com/jiekzou/
部落格版權:

本文以學習、研究和分享為主,歡迎轉載,但必須在文章頁面明顯位置給出原文連接配接。

如果文中有不妥或者錯誤的地方還望高手的你指出,以免誤人子弟。如果覺得本文對你有所幫助不如【推薦】一下!如果你有更好的建議,不如留言一起讨論,共同進步!

再次感謝您耐心的讀完本篇文章。

其它:

.net-QQ群4:612347965

java-QQ群:805741535

H5-QQ群:773766020

我的拙作《ASP.NET MVC企業級實戰》《H5+移動應用實戰開發》

《Vue.js 2.x實踐指南》

《JavaScript實用教程 》

《Node+MongoDB+React 項目實戰開發》

已經出版,希望大家多多支援!