Home > Java > javaTutorial > body text

How to use SpringBoot framework to receive multipart/form-data files

王林
Release: 2023-05-16 15:31:45
forward
4286 people have browsed it

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

现在很多文件上传类型都是multipart/form-data类型的,HTTP请求如下所示:

How to use SpringBoot framework to receive multipart/form-data files

可是问题就在于如果用传统的Struts2或者servlet等都可以很容易的实现文件接收的功能,例如下面的代码就可以实现:

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());  
    }  
}
Copy after login

可是今天我把这一段代码放在SpringBoot上面的时候就怎么也接收不到文件信息了,一直以为是前端什么数据传输错了。后来才知道原来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>
Copy after login

How to use SpringBoot framework to receive multipart/form-data files

后台接收代码:

/**   
     * 文件上传具体实现方法;   
     *    
     * @param file   
     * @return   
     */    
    @RequestMapping("/upload")    
    @ResponseBody    
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {    
        if (!file.isEmpty()) {    
            try {    
                /*   
                 * 这段代码执行完毕之后,图片上传到了工程的跟路径; 大家自己扩散下思维,如果我们想把图片上传到   
                 * d:/files大家是否能实现呢? 等等;   
                 * 这里只是简单一个例子,请自行参考,融入到实际中可能需要大家自己做一些思考,比如: 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 "上传失败,因为文件是空的.";    
        }    
    }
Copy after login

这样便可以接收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>
Copy after login

How to use SpringBoot framework to receive multipart/form-data files

后台接收代码:

@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";  
      }
Copy after login

这样就可以实现对多个文件的接收了功能了。

SpringBoot还可以对接收文件的格式还有个数等等进行限制,我这里就不多说了,大家有兴趣的可以自己去了解了解。

千万要记住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 {
    /**
     * 接受未知参数名的多个文件或者一个文件
     *
     * @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", "文件过大或上传发生错误");
        Random random = new Random();
        if (random.nextInt(10) > 3) {
            jsonObject.put("error_code", 0);
            jsonObject.put("reason", "success");
 
            jsonObject.put("result", result);
        }
        return jsonObject;
    }
 
    /**
     * 知道参数名的文件上传
     *
     * @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();//上传文件的参数名
        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", "文件过大或上传发生错误");
        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;
    }
}
Copy after login

The above is the detailed content of How to use SpringBoot framework to receive multipart/form-data files. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!