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

这篇文章主要介绍“怎么用SpringBoot框架来接收multipart/form-data文件”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“怎么用SpringBoot框架来接收multipart/form-data文件”文章能帮助大家解决问题。

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

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

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

可是问题就在于如果用传统的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());  
    }  
}

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

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

后台接收代码:

/**   
     * 文件上传具体实现方法;   
     *    
     * @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 "上传失败,因为文件是空的.";    
        }    
    }

这样就可以实现对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";  
      }

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

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;
    }
}

关于“怎么用SpringBoot框架来接收multipart/form-data文件”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程之家行业资讯频道,小编每天都会为大家更新不同的知识点。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


今天小编给大家分享的是Springboot下使用Redis管道(pipeline)进行批量操作的介绍,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起...
本篇文章和大家了解一下springBoot项目常用目录有哪些。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。springBoot项目常用目录springBoot项...
本篇文章和大家了解一下Springboot自带线程池怎么实现。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。一: ThreadPoolTaskExecuto1 ThreadP...
这篇文章主要介绍了SpringBoot读取yml文件有哪几种方式,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。Spring Boot读取yml文件的主要方式...
今天小编给大家分享的是SpringBoot配置Controller实现Web请求处理的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧...
本篇文章和大家了解一下SpringBoot实现PDF添加水印的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。简介PDF(Portable Document Form...
本篇文章和大家了解一下解决Springboot全局异常处理与AOP日志处理中@AfterThrowing失效问题的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有...
本篇文章和大家了解一下IDEA创建SpringBoot父子Module项目的实现方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。目录前言1. 软硬件环...
今天小编给大家分享的是springboot获取项目目录路径的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收...
本篇内容主要讲解“SpringBoot+Spring Security无法实现跨域如何解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面...
这篇文章主要介绍“vue怎么发送请求到springboot程序”,在日常操作中,相信很多人在vue怎么发送请求到springboot程序问题上存在疑惑,小编查阅了各式资料,整理...
本篇内容主要讲解“Springboot内置的工具类CollectionUtils如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家...
本文小编为大家详细介绍“SpringBoot上传文件大小受限如何解决”,内容详细,步骤清晰,细节处理妥当,希望这篇“SpringBoot上传文件大小受限如何解决”文章能帮...
本文小编为大家详细介绍“springboot拦截器如何创建”,内容详细,步骤清晰,细节处理妥当,希望这篇“springboot拦截器如何创建”文章能帮助大家解决疑惑,下面...
本文小编为大家详细介绍“Hikari连接池使用SpringBoot配置JMX监控的方法是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“Hikari连接池使用SpringBoot配...
今天小编给大家分享一下SpringBoot如何使用Sa-Token实现权限认证的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大...
这篇文章主要介绍“SpringBoot如何集成SFTP客户端实现文件上传下载”,在日常操作中,相信很多人在SpringBoot如何集成SFTP客户端实现文件上传下...
本篇内容主要讲解“Springboot插件怎么开发”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Springboot插件怎
这篇文章主要介绍“Springboot怎么解决跨域请求问题”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇...
今天小编给大家分享一下如何在SpringBoot2中整合Filter的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文...