导入文件上传实现需要的jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
- 传统的文件上传
1.编写控制器方法
@RequestMapping("/testFileUpload")
public String testFileUpload(HttpServletRequest request) throws Exception {
//获取上传的文件路径
String path = request.getSession().getServletContext().getRealPath("/upload/");
//创建文件夹对象
File file = new File(path);
//判断是否存在
if(!file.exists()){
// 不存在则创建
file.mkdir();
}
// 创建磁盘文件项工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//解析在request中的内容
List<FileItem> fileItems = fileUpload.parseRequest(request);
//遍历文件项
for (FileItem fileItem:fileItems){
if (fileItem.isFormField()){
}else {
//获取文件的文件名并拼装
String fileName = fileItem.getName();
String uuid = UUID.randomUUID().toString();
fileName = uuid + "_" + fileName;
//写入
fileItem.write(new File(path,fileName));
//删除缓存
fileItem.delete();
}
}
return "success";
}
2.配置文件解析器
<!-- 配置文件上传解析器 -->
<bean id="multipartResolver" <!-- id 的值是固定的-->
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为 5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
- springmvc实现的文件上传
@RequestMapping("/testSpringmvcFileUpload")
public String testFileUpload(HttpServletRequest request, MultipartFile upload) throws Exception {
//获取文件上传的路径
String path = request.getSession().getServletContext().getRealPath("/upload/");
//创建文件夹对象
File file = new File(path);
//判断是否存在
if (!file.exists()) {
// 不存在则创建
file.mkdir();
}
//设置文件名
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString();
filename = uuid + "_" + filename;
//上传
upload.transferTo(new File(path, filename));
return "success";
}
这里的MultipartFile的参数名必须与表单中name一致.
然后配置文件解析器
- springmvc 跨服务器方式的文件上传
1.导入jersey包
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
2.编写控制器方法
@RequestMapping("/testTwoFileUpload")
public String testTwoFileUpload(MultipartFile upload) throws Exception {
//获取文件上传服务器地址
String path = "http://localhost:9090/fileUploadServer_war_exploded/uploads/";
//更改文件名称
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString();
filename = uuid + "_" + filename;
//上传
Client client = Client.create();
WebResource resource = client.resource(path+filename);
resource.put(upload.getBytes());
return "success";
}
3.配置文件解析器