SpringMVC框架提供了MultipartFile对象,该对象表示上传的文件,要求变量名称必须和表单file标签的 name属性名称相同。
在pom.xml上添加文件上传依赖的jar
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
在Springmvc.xml 上配置文件解析器对象,要求id名称必须是multipartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 文件最大字节数 -->
<property name="maxUploadSize" value="10485760"/>
</bean>
上传的界面。即jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文件上传</title>
</head>
<body>
<form action="fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="上传">
</form>
</body>
</html>
上传的核心
package com.hadwinling.controller;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
@Controller
@SessionAttributes(value="userimg")
public class FileUpLoadController {
@RequestMapping("/fileUpload")
public String fileUpload(MultipartFile file,ModelMap map) throws IllegalStateException, IOException {
String savePath="E:\\upload";
File saveFile=new File(savePath);
if(!saveFile.exists()) {
saveFile.mkdirs();
}
//获取文件名
String fileName=file.getOriginalFilename();
String uuid=UUID.randomUUID().toString().replace("-", "").toLowerCase();
//将文件名唯一话
fileName=uuid+fileName;
System.out.println(fileName);
//实现上传
file.transferTo(new File(saveFile,fileName));
//service 保存图片的上传路径
//使用第三方 七牛云,保存图片的上传路径 http://
//本地图片保存 保存到数据库时,不要保存磁盘路径。保存文件名
//保存在session中 模拟从数据库中查询到的文件路径
map.addAttribute("userimg", fileName);
//在main页面中显示图片
return "redirect:demo01/fileupload";
}
}
在Tomcat中配置虚拟路径
server.xml
docBase:物理路径
path:虚拟路径
<Context docBase="E:\upload" path="/FileDir"/>
其中server.xml文件在
进入到server.xml后
回显:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<c:if test="${userimg!=null }">
<!-- src:
图片的物理路径是在E:\\upload\\
不使用物理路径,使用虚拟路径
tomcat的server.xml中配置虚拟路径-->
<img src="/FileDir/${userimg }" width="200px" height="200px">
</c:if>
</body>
</html>
文件结构: