1. 程式人生 > 程式設計 >SpringBoot實現單檔案與多檔案上傳功能

SpringBoot實現單檔案與多檔案上傳功能

目錄
  • 1.單檔案上傳
  • 2.多檔案上傳

1.單檔案上傳

首先建立一個Spring Boot專案,並新增spring-boot-starter-web依賴

然後建立一個upload.p檔案,做一個簡單的檔案上傳頁面,具體程式碼如下:

<%@ page contentType="text/html;charset=UTF-8" language="" %>
<html>
<head>
  <title>Title</title>
</head>
<body>
  <form action="${pageContext.request.contextPath}/wjsc/upload" method="post" enctype="multipart/form-data">
    <input type="file" value="請選擇檔案" name="uploadFile">
    <input type="submit" value="點選上傳">
; </form> </body> </html>

上傳介面是wjsc/upload,注意請求方法是postenctypemultipart/form-data

然後建立上傳檔案介面:

@RequestMapping("/wjsc")
@RestController
public class UploadController {
  /**
  * 檔案上傳
  */
  @PostMapping("/upload")
  //MultipartFile接受前臺傳過來的檔案
  public String upload(MultipartFile uploadFile,HttpServletRequest req){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
    //設定上傳檔案的儲存路徑為專案執行目錄下的uploadFile資料夾
    String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/");
    //獲取當前日期對所上傳的檔案進行歸類儲存
    String format = sdf.format(new Date());
    File folder = new File(realPath+format);
    if (!folder.isDirectory()){//判斷是否為目錄
      folder.mkdirs();//不是目錄就建立目錄
    }
    //給上傳的檔案重新命名
    String oldName = uploadFile.getOriginalFilename();//獲取檔名稱
    String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());//設定新檔名
    try{
      //檔案儲存操作
      uploadFile.transferTo(new File(folder,newName));
      //www.cppcns.com
生成檔案訪問路徑 String filePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/uploadFile/"+format+newName; return filePath; }catch (Exception e){ e.printStackTrace(); 客棧 程式設計客棧 } return "上傳失敗"; } }

注意:MultipartFile變數名命名要與jsp中上傳檔案的name一致,不然會接收不到檔案

最後測試:

執行專案,在瀏覽器中訪問upload.jsp

頁面進行檔案上傳

SpringBoot實現單檔案與多檔案上傳功能

上傳成功後會返回檔案訪問路徑,用這個路徑就可以訪問到剛剛上傳的圖片

SpringBoot實現單檔案與多檔案上傳功能

專案中也可以看到剛剛上傳的圖片成功了

SpringBoot實現單檔案與多檔案上傳功能

至此,一個簡單的單檔案上傳就完成了.

2.多檔案上傳

多檔案上傳和單檔案上傳基本一致,首先修改jsp檔案,程式碼如下:

<

%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<程式設計客棧head>
  <title>Title</title>
</head>
<body>
  <form action="${pageContext.request.contextPath}/wjsc/upload" method="post" enctype="multipart/form-data">
    <input type="file" value="請選擇檔案" name="uploadFiles" multiple>
    <input type="submit" value="點選上傳">
  </form>
</body>
</html>

然後修改上傳檔案介面:

/**
  * 多檔案上傳
  */
  @PostMapping("/uploads")
  public String uploads(MultipartFile[] uploadFiles,HttpServletRequest req) {
    //遍歷uploadFiles陣列分別儲存
  }

控制器裡邊的核心邏輯和單檔案上傳是一樣的,只是多一個遍歷的步驟。

到此這篇關於SpringBoot實現單檔案與多檔案上傳功能的文章就介紹到這了,更多相關SpringBoot實現檔案上傳功能內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!