第一步:springmvc 中文件上传控制器层
package com.aaa.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
// @RestController相当于@Controller+@ResponseBody两个注解的结合,
// 返回json数据不需要在方法前面加@ResponseBody注解了,
// 但使用@RestController这个注解,就不能返回jsp,html页面,
// 视图解析器无法解析jsp,html页面
@RestController
//@Controller
public class FileController {
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存位置
String path=request.getServletContext().getRealPath("/upload");
File realPath=new File(path);
if(!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件的地址"+realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
return "redirect:index.jsp";
}
/*文件上传*/
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public String upload(String yourName, MultipartFile photo,HttpServletRequest request){
//获取到文件准备上传到的路径
String path = request.getServletContext().getRealPath("/attachements");
//获取到文件流
File realPath=new File(path);
//判断这个文件的路径是否存在 ,如果不存在则进行新建
if(!realPath.exists()){
realPath.mkdir();
}
//获取到文件的后缀
//getOriginalFilename() 获取到上传文件的名称 例如:10.jpg
String substring = photo.getOriginalFilename().substring(photo.getOriginalFilename().indexOf("."));
//File.separator 获取到文件的分隔符 可以在任何系统中使用
File file=new File(path+File.separator+ UUID.randomUUID().toString() +substring);
try {
photo.transferTo(file);
System.out.println(file);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
jsp页面
<form method="post" enctype="multipart/form-data" action="/test/upload">
Names:<input type="text" name="yousName" id=""><br/>
Photo:<input type="file" name="photo"/><br/>
<button type="submit">上传</button>
</form>
文件上传的依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
最后一步:配置mvc.xml 中文件上传解析器
<!--配置文件上传解析器-->
<!--id 必须是multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--默认的的编码格式-->
<property name="defaultEncoding" value="UTF-8"/>
<!--文件能够上传的大小-->
<property name="maxUploadSize" value="#{1024*1024*10}"/>
</bean>