Spring MVC 上下文中默认没有为文件上传提供了直接的支持,因 此默认情况下不能处理文件的上传工作,如果想使用 Spring 的文件上传功能,需现在上下文中配置 CommonsMultipartResovler:
1.加入jar包:
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
2.在SpringMVC配置文件中配置CommonsMultipartResovler
<!-- 配置CommonsMultipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<!-- 以字节为单位 -->
<property name="maxUploadSize" value="1024000"></property>
</bean>
3.表单:POST请求,file类型,enctype="multipart/form-data"
1.文件下载
[1]输入流、输出流原生方法实现
@RequestMapping(value="/testDownload")
public void testDownload(HttpServletRequest request,HttpServletResponse response) throws IOException{
ServletContext servletContext=request.getServletContext();
String fileName="风吹麦浪.mp3";
String path = servletContext.getRealPath("WEB-INF/upload/"+fileName);
System.out.println(path);
File file=new File(path);
String type = servletContext.getMimeType(path);
InputStream inputStream=new FileInputStream(file);
response.setContentType(type);
fileName=new String(fileName.getBytes("gbk"),"iso8859-1");
response.setHeader("Content-Disposition","attachment;filename="+fileName);
ServletOutputStream outputStream=response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
}
[2]输入流和ResponseEntity实现:
@RequestMapping(value="/testDownload")
public ResponseEntity<byte[]> testDownload(HttpServletRequest request) throws IOException{
//声明缓冲区
byte[] body = null;
//确定下载文件名
String fileName = "风吹麦浪.mp3";
//获取文件真实路径
ServletContext servletContext = request.getServletContext();
String path = servletContext.getRealPath("/WEB-INF/upload/"+fileName);
//新建输入流
File file = new File(path);
InputStream in = new FileInputStream(file);
//为缓冲区设置大小
body = new byte[in.available()];
//缓冲区读入文件内容
in.read(body);
//修改文件名格式,使页面可以展示
fileName = new String(fileName.getBytes("gbk"),"iso8859-1");
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename="+fileName);
//设置请求状态
HttpStatus statusCode=HttpStatus.OK;
//
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
return response;
}
2.文件、资源上传到服务器
[1]通过FileItem实现
@RequestMapping(value="/testUpload",method=RequestMethod.POST)
public String testUpload(@RequestParam(value="desc") String desc,@RequestParam("photo") CommonsMultipartFile file,HttpServletRequest request){
System.out.println(desc);
try {
FileItem fi=file.getFileItem();
//获取文件名
String fileName = file.getOriginalFilename();
if(fileName.contains("\\")){
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
}
System.out.println("fileName:"+fileName);
//获取上传路径
String realPath = request.getRealPath("/WEB-INF/upload");
String realPath2 = request.getServletContext().getRealPath("/WEB-INF/upload");
System.out.println(realPath2);
//检查upload文件夹是否存在,如果不存在则创建
System.out.println(realPath);
File file1 = new File(realPath);
if(!file1.exists()){
file1.mkdirs();
};
//为避免重名生成一个uuid作为文件名的前缀
String prefix = UUID.randomUUID().toString().replace("-", "");
//将文件写入到服务器中
fi.write(new File(realPath+"/"+prefix+"_"+fileName));
//清楚文件缓存
fi.delete();
} catch(FileSizeLimitExceededException e){
System.out.println("文件内容太大,无法上传");
}catch ( Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
[2]使用原生方法实现:
@RequestMapping(value="/testUpload",method=RequestMethod.POST)
public String testUpload(@RequestParam(value="desc") String desc,@RequestParam("photo") CommonsMultipartFile file,HttpServletRequest request){
InputStream in=null;OutputStream out=null;
ServletContext servletContext=request.getServletContext();
String realPath = servletContext.getRealPath("/WEB-INF/upload");
String fileName=file.getOriginalFilename();
UUID id=UUID.randomUUID();
fileName=id+"_"+fileName;
System.out.println(realPath);
File file1=new File(realPath);
if(!file1.exists()){
file1.mkdirs();
}
try {
in=file.getInputStream();
out=new FileOutputStream(new File(realPath+"\\"+fileName));
byte[] buffer=new byte[1024];
int len=0;
while((len=in.read(buffer))!=-1){
out.write(buffer, 0, len);
}
/*IOUtils.copy(in, out);*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return "json";
}