什么是MultipartFile
MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。【来自百度知道】
byte[] | getBytes() 以字节数组的形式返回文件的内容。 |
String | getContentType 返回文件的内容类型。 |
FileItem | getFileItem() 返回底层的org.apache.commons.fileupload.FileItem实例。 |
InputStream | getInputStream() 返回一个InputStream来读取文件的内容。 |
String | getName() 以multipart 表格的形式返回参数的名称。 |
String | getOriginalFileName() 返回客户机文件系统中的原始文件名。 |
long | getSize() 以字节的形式返回文件的大小 |
String | getStorageDescription() 返回multipart的内容和存储位置描述。 |
protected boolean | isAvailable() 确定Multipart内容是否仍然可用。 |
boolean | isEmpty() 返回上传的文件是否为空,也就是说,在多部分表单中没有选择任何文件,或者选择的文件没有内容。 |
void | transferTo(File dest) 将接收到的文件传输到给定的目标文件。 |
基于springboot+maven的项目中实现文件上传
单文件上传
前段HTML页面:
<form id="uploadForm" enctype = "multipart/form-data">
<input type ="text" id ="uploadParams" vlaue = "uploadParams" />
<input type = "file" name = "uploadfile" id = "uploadfile" />
<input type = "button" id = "btnSave" onclick = "uploadSubmit()" />
</form>
JS处理,需要引用JQuery.js
function uploadSubmit() {
if (!$("#uploadfile").val()) {
console.log("上传失败,文件是空的");
return false;
}
var paramValue = $("#uploadParams").val();
var formData = new FormData(document.getElementById('uploadForm'));
formData.append("paramValue",paramValue);
$.ajax({
url: "your server url",
type: "post",
data: formdata,
dataType: "json",
processData: false,
contentType: false,
success: function (result) {
console.log("上传成功");
},
error: function (a, b, c) {
console.log("失败了");
},
complete: function () {
console.log("请求最后处理的方法");
},
})
}
FormData对象的使用
FormData对象用以将数据编译成键值对,以便用XMLHttpRequest来发送数据。其主要用于发送表单数据,但亦可用于发送带键数据(keyed data),而独立于表单使用。如果表单enctype
属性设为multipart/form-data ,则会使用表单的submit()方法来发送数据,从而,发送数据具有同样形式。
可以创建一个FormData对象,然后调用它的append()方法来添加字段。
后台Java处理:
pom.xml中添加依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
servlet-context.xml中配置bean:
<!-- 扫描器 -->
<context:component-scan base-package="com.doujinxain"/>
<!-- 环境配置文件扫描器 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:path.properties</value>
</list>
</property>
</bean>
<beans>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
</beans>
@RequestMapping("upload")
public String upload(@RequestParam("uploadfile") MultipartFile file,@RequestParam("paramValue") String paramvalue,HttpServletRequest request){
try{
//得到文件"upload"的服务器路径
String sysPath=request.getSession().getServletContext().getRealPath("upload");
String fileName=file.getOriginalFilename(); //得到文件名
File filePath=new File(sysPath,fileName); //得到文件路径
if(!filePath.getParentFile().exists()){ //判断服务器当前路径文件夹是否存在
filePath.getParentFile().mkdirs(); //不存在则创建文件夹
}
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(filePath));
out.write(file.getBytes());
out.flush();
out.close();
}catch(fileNotFoundException e){
e.printStrackTrace();
return "失败";
}catch(IOException e){
e.printStrackTrace();
return "失败";
}
}
BufferedOutputStream(缓冲输出流),继承于FilterOutputStrema,它的作用是为另一个输出流提供“缓冲功能”,该类实现一个缓冲输出流。通过设置这样的输出流,应用程序可以将字节写入底层输出流,而不必为写入的每个字节调用底层系统。
方法总结 | |
修饰符和类型 | 方法和描述 |
void | flush() 刷新此缓冲输出流。 |
void | write(byte[] b,int off,int len) 从指定字节数组的偏移处开始将len字节写入此缓冲输出流。 |
void | write(int b) 将指定的字节写入此缓冲输出流。 |
多文件上传:
与单文件差别不大:前端多个<input type="file">,后端接收的时候方法参数使用数组:
@RequestParam("param") MultipartFile [] file
附:
基于springboot+maven实现简单的字符串上传服务器
package com.doujinxain.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/restful")
public class DataProcessController {
@RequestMapping("/uploadString")
public String imageProcess(@RequestParam("param") String receiveString)
{
System.out.println(receiveString);
return receiveString;
}
}
客户端通过:http://localhost:8080/service_name/restful/uploadString?param="test"
其中@RequestParam(””)将参数param和字符串receiveString绑定。
参考:Multipart 官方API