1.文件上传
文件上传是项目开发中常用的功能。为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这种情况下,浏览器才会把用户选择的文件二进制数据发送给服务器。
Spring MVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。Spring MVC使用Apache Commons fileupload技术实现了一个MultipartResolver实现类:CommonsMultipartResolver.所以Spring MVC的文件上传依赖Apache Commons fileupload的组件。
2.MultipartFile
Spring MVC会将上传文件绑定到MultipartFile对象中,该对象提供了获取上传文件内容,文件名等方法。通过transferTo()方法还可以将文件存储到硬件中。
MultipartFile常用方法如下:
*bye[] getBytes() :获取文件数据
*String getContentType() :获取文件MIME类型
*InputStream getIputStream() :获取文件流
*String getName() :获取表单中文件组件的名字
*String getOriginalFilename() :获取上传文件的原名
*boolean isEmpty() :是否有上传的文件
*void transferTo(File dest) :将文件保存到一个目标文件中
3.实例(IDEA环境)
3.1 导入相应的jar包
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
3.2 配置springmvc-config.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小上限,单位为字节(10MB) -->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
3.3 编写Controller
/**
* @author Ray
* @date 2018/4/21 0021
*/
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/toFile")
public String toFileUpload(){
return "fileUpload";
}
/**
* 上传文件
* @param file
* @param request
* @param model
* @return
*/
@RequestMapping("/onefile")
public String oneFileUpload(@RequestParam("file")CommonsMultipartFile file,
HttpServletRequest request, Model model){
//获取原始文件名
String fileName = file.getOriginalFilename();
System.out.println("原始文件名:" + fileName);
//新文件名
String newFileName = UUID.randomUUID() + fileName;
//获取项目路径
// ServletContext servletContext = request.getSession().getServletContext();
//上传位置
// String path = servletContext.getRealPath("/upload") + "/"; //项目路径/upload文件夹
String path = "F:\\test\\"; //本地路径/test
File f = new File(path);
if(!f.exists()){
f.mkdirs();
}
if(!file.isEmpty()){
try{
FileOutputStream fileOutputStream = new FileOutputStream(path + newFileName);
InputStream inputStream = file.getInputStream();
int b = 0;
while ((b = inputStream.read()) != -1){
fileOutputStream.write(b);
}
fileOutputStream.close();
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
//控制台输出
System.out.println("上传图片到:" + path + newFileName);
//保存文件地址,用于JSP页面回显
model.addAttribute("fileUrl",newFileName);
return "fileUpload";
}
}
3.4 编写fileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Insert title here</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<center>
<form action="file/onefile"
method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上 传" />
</form>
<h5>上传结果:</h5>
<img src="/files/${fileUrl}" alt="暂无图片">
</center>
</body>
</html>
3.5 测试运行
成功!
3.6 错误Not allowed to load local resource
chrome报Not allowed to load local resource错误
解决办法: 查看原文