How to use SpringBoot framework to receive multipart/form-data files
SpringBoot框架接收multipart/form-data文件
现在很多文件上传类型都是multipart/form-data类型的,HTTP请求如下所示:
可是问题就在于如果用传统的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框架
前台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>
后台接收代码:
/** * 文件上传具体实现方法; * * @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>
后台接收代码:
@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; } }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic
