溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么用SpringBoot框架來接收multipart/form-data文件

發(fā)布時間:2023-02-27 11:05:58 來源:億速云 閱讀:146 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“怎么用SpringBoot框架來接收multipart/form-data文件”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“怎么用SpringBoot框架來接收multipart/form-data文件”文章能幫助大家解決問題。

SpringBoot框架接收multipart/form-data文件

現(xiàn)在很多文件上傳類型都是multipart/form-data類型的,HTTP請求如下所示:

怎么用SpringBoot框架來接收multipart/form-data文件

可是問題就在于如果用傳統(tǒng)的Struts2或者servlet等都可以很容易的實現(xiàn)文件接收的功能,例如下面的代碼就可以實現(xiàn):

boolean isMultipart = ServletFileUpload.isMultipartContent(request);//判斷是否是表單文件類型  
DiskFileItemFactory factory = new DiskFileItemFactory();  
ServletFileUpload sfu = new ServletFileUpload(factory);  
List items = sfu.parseRequest(request);//從request得到所有上傳域的列表  
for(Iterator iter = items.iterator();iter.hasNext();){  
    FileItem fileitem =(FileItem) iter.next();  
    if(!fileitem.isFormField()&&fileitem!=null){//判讀不是普通表單域即是file  
        System.out.println("name:"+fileitem.getName());  
    }  
}

可是今天我把這一段代碼放在SpringBoot上面的時候就怎么也接收不到文件信息了,一直以為是前端什么數(shù)據(jù)傳輸錯了。后來才知道原來SpringBoot有它自己的接收請求的代碼。下面就給大家詳細(xì)介紹一下它是如何實現(xiàn)這個功能的。

首選做一個簡單的案例,也就是單個文件上傳的案例。(這個案例是基于SpringBoot上面的,所以大家首先得搭建好SpringBoot這個框架)

前臺HTML代碼:

<html>  
<body>  
  <form action="/upload" method="POST" enctype="multipart/form-data">  
    <input type="file" name="file"/>  
    <input type="submit" value="Upload"/>   
  </form>  
</body>  
</html>

怎么用SpringBoot框架來接收multipart/form-data文件

后臺接收代碼:

/**   
     * 文件上傳具體實現(xiàn)方法;   
     *    
     * @param file   
     * @return   
     */    
    @RequestMapping("/upload")    
    @ResponseBody    
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {    
        if (!file.isEmpty()) {    
            try {    
                /*   
                 * 這段代碼執(zhí)行完畢之后,圖片上傳到了工程的跟路徑; 大家自己擴散下思維,如果我們想把圖片上傳到   
                 * d:/files大家是否能實現(xiàn)呢? 等等;   
                 * 這里只是簡單一個例子,請自行參考,融入到實際中可能需要大家自己做一些思考,比如: 1、文件路徑; 2、文件名;   
                 * 3、文件格式; 4、文件大小的限制;   
                 */    
                BufferedOutputStream out = new BufferedOutputStream(    
                        new FileOutputStream(new File(    
                                file.getOriginalFilename())));    
                System.out.println(file.getName());  
                out.write(file.getBytes());    
                out.flush();    
                out.close();    
            } catch (FileNotFoundException e) {    
                e.printStackTrace();    
                return "上傳失敗," + e.getMessage();    
            } catch (IOException e) {    
                e.printStackTrace();    
                return "上傳失敗," + e.getMessage();    
            }    
    
            return "上傳成功";    
    
        } else {    
            return "上傳失敗,因為文件是空的.";    
        }    
    }

這樣就可以實現(xiàn)對multipart/form-data類型文件的接收了。那如果是多個文件外加多個字段呢,下面接著看下一個多個文件上傳的案例。

前臺HTML界面:

<!DOCTYPE html>    
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"    
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">    
    <head>    
        <title>Hello World!</title>    
    </head>    
    <body>    
       <form method="POST" enctype="multipart/form-data" action="/batch/upload">     
           <p>文件1:<input type="text" name="id" /></p>    
           <p>文件2:<input type="text" name="name" /></p>    
           <p>文件3:<input type="file" name="file" /></p>    
           <p><input type="submit" value="上傳" /></p>    
       </form>    
    </body>    
</html>

怎么用SpringBoot框架來接收multipart/form-data文件

后臺接收代碼:

@RequestMapping(value = "/batch/upload", method = RequestMethod.POST)    
      @ResponseBody    
      public String handleFileUpload(HttpServletRequest request) {    
        MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);  
          List<MultipartFile> files = ((MultipartHttpServletRequest) request)    
                  .getFiles("file");   
          String name=params.getParameter("name");  
          System.out.println("name:"+name);  
          String id=params.getParameter("id");  
          System.out.println("id:"+id);  
          MultipartFile file = null;    
          BufferedOutputStream stream = null;    
          for (int i = 0; i < files.size(); ++i) {    
              file = files.get(i);    
              if (!file.isEmpty()) {    
                  try {    
                      byte[] bytes = file.getBytes();    
                      stream = new BufferedOutputStream(new FileOutputStream(    
                              new File(file.getOriginalFilename())));    
                      stream.write(bytes);    
                      stream.close();    
                  } catch (Exception e) {    
                      stream = null;    
                      return "You failed to upload " + i + " => "    
                              + e.getMessage();  
                  }    
              } else {    
                  return "You failed to upload " + i    
                          + " because the file was empty.";    
              }  
          }    
          return "upload successful";  
      }

這樣就可以實現(xiàn)對多個文件的接收了功能了。

SpringBoot還可以對接收文件的格式還有個數(shù)等等進行限制,我這里就不多說了,大家有興趣的可以自己去了解了解。

千萬要記住SpringBoot對multipart/form-data類型的文件接收和其它是不一樣的,大家以后遇到的時候要千萬小心,不要像我一樣一往無前的踩進去還傻傻的以為是前端的錯誤。

SpringBoot接收文件

package cn.juhe.controller;
 
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
 
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
 
@RestController
public class UploadTest {
    /**
     * 接受未知參數(shù)名的多個文件或者一個文件
     *
     * @param request 請求
     * @return 返回
     */
    @PostMapping("/upload")
    public JSONObject handleFileUpload(HttpServletRequest request) {
        Iterator<String> fileNames = ((MultipartHttpServletRequest) request).getFileNames();
        JSONObject result = null;
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            MultipartFile file = ((MultipartHttpServletRequest) request).getFile(next);
            System.out.println("file.getName():" + file.getName());
            System.out.println("file.getOriginalFilename():" + file.getOriginalFilename());
            String folder = "E:\\upload\\received\\";
            String picName = new Date().getTime() + ".jpg";
            File filelocal = new File(folder, picName);
            result = new JSONObject();
            result.put(picName, folder + picName);
            try {
                file.transferTo(filelocal);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error_code", 223805);
        jsonObject.put("reason", "文件過大或上傳發(fā)生錯誤");
        Random random = new Random();
        if (random.nextInt(10) > 3) {
            jsonObject.put("error_code", 0);
            jsonObject.put("reason", "success");
 
            jsonObject.put("result", result);
        }
        return jsonObject;
    }
 
    /**
     * 知道參數(shù)名的文件上傳
     *
     * @param multipartFile 文件
     * @return 返回
     * @throws IOException
     */
    @PostMapping("/uploadCommon")
    //public JSONObject upload(MultipartFile multipartFile) throws IOException {
    public JSONObject upload(@RequestParam("A") MultipartFile multipartFile) throws IOException {
        String name = multipartFile.getName();//上傳文件的參數(shù)名
        String originalFilename = multipartFile.getOriginalFilename();//上傳文件的文件路徑名
        long size = multipartFile.getSize();//文件大小
        String folder = "E:\\upload\\received\\";
        String picName = new Date().getTime() + ".jpg";
        File filelocal = new File(folder, picName);
        multipartFile.transferTo(filelocal);
       /* {
            "reason": "success",
                "result": {
            "D": "/upload/order/files/2016/a72750ad-8950-4949-b04a-37e69aff0d23.jpg",
                    "A": "/upload/order/files/2016/6842811a-eb76-453b-a2f3-488e2bb4500e.jpg",
                    "B": "/upload/order/files/2016/ccc96347-3cb8-4e2e-99a3-0c697b57eb88.jpg",
                    "C": "/upload/order/files/2016/d470d533-a54b-406a-a0f9-bbf82c314755.jpg"
        },
            "error_code": 0
        }*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error_code", 223805);
        jsonObject.put("reason", "文件過大或上傳發(fā)生錯誤");
        Random random = new Random();
        if (random.nextInt(10) > 3) {
            jsonObject.put("error_code", 0);
            jsonObject.put("reason", "success");
            JSONObject result = new JSONObject();
            result.put(name, folder + picName);
            jsonObject.put("result", result);
        }
        return jsonObject;
    }
}

關(guān)于“怎么用SpringBoot框架來接收multipart/form-data文件”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI