用SpringBoot框架来接收multipart/form-data文件方式
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上面的,所以大家首先得搭建好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>
后台接收代码:
@RequestMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
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 {
@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;
}
@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);
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;
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
相关文章