SpringMVC的文件上传
1. 创建项目,完善结构,导入依赖,配置web.xml
<!-- 配置开发SpringMVC所以来的jar包 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- 配置ServletAPI依赖 -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- commons-fileupload组件 -->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2. 创建SpringMVC配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--配置自动扫描包-->
<context:component-scan base-package="com.wangxing.springmvc.controller"></context:component-scan>
<!-- 视图解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--maxUploadSize上传文件的大小 -->
<property name="maxUploadSize" value="104857600" />
<!--maxInMemorySize内存大小 -->
<property name="maxInMemorySize" value="4096" />
<!--defaultEncoding默认字符编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
</beans>
3. 创建文件上传页面,和成功的页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<!--
1.form表单的method属性一定是post
2.enctype属性一定要设置且取值multipart/form-data
enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码
application/x-www-form-urlencoded----在发送前编码所有字符(默认)
multipart/form-data----不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。
text/plain---空格转换为 "+" 加号,但不对特殊字符编码。
3.文件上传控件---<input type="file" name="myfile">
-->
<form action="upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="myfile"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
4. 创建处理文件上传请求的控制器
package com.wangxing.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Iterator;
//文件上传控制器
@Controller
public class UploadController {
@RequestMapping(value = "/upload.do",method = RequestMethod.POST)
public ModelAndView upload(HttpServletRequest request)throws Exception{
ModelAndView mav=new ModelAndView();
//处理包含有文件的http请求
//1. 将当前类中的ServletContext对象转换成CommonsMultipartResolver
ServletContext servletContext=request.getSession().getServletContext();
CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver(servletContext);
//2.检验HttpServletRequest是否是一个文件上传请求
if(commonsMultipartResolver.isMultipart(request)){
//3.将HttpServletRequest请求转换成文件上传请求
MultipartHttpServletRequest multipartreq=(MultipartHttpServletRequest)request;
//4.从文件上传请求中得到得到文件名称
Iterator<String> itname=multipartreq.getFileNames();
while(itname.hasNext()){
//得到input元素的name属性值
String nameshuxing=itname.next().toString(); //myfile
//根据name属性值得到上传来的文件对象
MultipartFile multipartfile=multipartreq.getFile(nameshuxing);
String newfilename=""; //保存上传来的文件的名称
if(multipartfile!=null){
//得到被上传来的文件的真实名称【test.html】
String zhenFileName=multipartfile.getOriginalFilename();
//得到文件的后缀名[.html]
String houzhuiming=zhenFileName.substring(zhenFileName.lastIndexOf("."));
//得到系统时间的毫秒数,将来作为文件的名称
long haomiaoshu=System.currentTimeMillis();
newfilename=haomiaoshu+houzhuiming;
//获取项目的根目录
String realPath = servletContext.getRealPath("/upload");
//创建保存文件的目录
File uploadpicdir = new File(realPath);
if(!uploadpicdir.exists()){
//创建upload目录
uploadpicdir.mkdirs();
}
//组织一个保存文件的对象【文件保存目录+文件名称】
String pathfile=uploadpicdir.getAbsolutePath()+File.separator+newfilename;
System.out.println(pathfile);
File saveFile=new File(pathfile);
//保存文件到本地磁盘
multipartfile.transferTo(saveFile);
}
//得到上传成功以后的文件的http访问地址
String reqURL=request.getRequestURL().toString();
reqURL=reqURL.substring(0,reqURL.lastIndexOf("/"));
reqURL=reqURL+"/upload/"+newfilename;
//http://127.0.0.1:8080/upload/xxxxxx.jpg
System.out.println("reqURL=="+reqURL);
}
mav.setViewName("success.html");
}
return mav;
}
}
5. 部署测试
SpringMVC的文件下载
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<h1><a href="dowload.do?myfile=avatar.png">下载avatar.png</h1>
<h1><a href="dowload.do?myfile=bgcolor.html">下载bgcolor.html</h1>
</body>
</html>
package com.wangxing.springmvc.controller;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
@Controller
public class DowloadController {
@RequestMapping(value = "/dowload.do",method = RequestMethod.GET)
public ResponseEntity<byte[]> dowloadMethod(HttpServletRequest req)throws Exception{
//得到请求中的文件名称
String filename=req.getParameter("myfile");
String realPath = req.getSession().getServletContext().getRealPath("/upload");
//创建保存文件的目录的文件对象
File uploadpicdir = new File(realPath);
//创建被下载的文件对象
File file=new File(uploadpicdir,filename);
System.out.println(file.getAbsolutePath());
//设置http协议头
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment",filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
}