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>
文件結構: