springMVC上傳文件,使用MultipartHttpServletRequest、MultipartFile進行文件上傳


轉自博主:https://blog.csdn.net/qq_35525955/article/details/80904844#commentBox

這里使用apache的開源jar包完成上傳功能,使用jar包分別是:common-fileupload.jar和common-io.jar

所需jar包

先編寫上傳文件幫助類,如果需要區分文件類型,可以將文件后綴截取進行判斷;

springmvc-mvc.xml配置,這里主要配置springmvc解析器CommonsMultipartResolver等等,這里主要是配置文件上傳解析器,下面是配置文件代碼:

<?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:p="http://www.springframework.org/schema/p"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- 自動掃描該包,使SpringMVC認為包下用了@controller注解的類是控制器 -->
<context:component-scan base-package="com.cw.cashier.controller.*" />

<!--避免IE執行AJAX時,返回JSON出現下載文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>

<!-- 使用注解 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>

<!-- 不處理靜態資源 -->
<mvc:default-servlet-handler />

<!-- 上傳文件時需要用到的分解層,默認將編碼轉為urf-8,設置最大上傳容量 ,最大內存-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<property name="maxUploadSize" value="102400000" />
<property name="maxInMemorySize" value="4096" />
</bean>

<!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前后綴 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>

</beans>

編寫文件上傳幫助類

注意:文件上傳時,會有上傳多個文件的功能,所以文件上傳幫助類方法可以寫成返回 List 集合,
這樣就可以基本滿足單個和多個文件上傳使用,不多說了,上代碼:

/**
* 上傳文件幫助類
*
* @author ajie
*
*/
public class FileUploadUtil {
// 使用日志工廠獲取日志對象
private static Log log = LogFactory.getLog(FileUploadUtil.class);

/**
* 批量上傳文件
*
* @param request
* @param response
* @param username
* 用戶名; 用於區分用戶上傳的圖片
* @param moduleName
* 模塊名稱; 用於區分該圖片是位於那個模塊進行上傳
* @return
* @throws FileNotFoundException
*/
public static List<String> uploadFile(HttpServletRequest request, String username,
String moduleName) throws FileNotFoundException {

// 創建list集合,用於接收上傳文件的路徑
List<String> filePathList = new ArrayList<String>();

// 拼接文件上傳位置,這里使用Tomcat服務器,將文件上傳到webapps中,和項目同目錄,files將用於保存上傳的文件,將上傳的文件於項目分開
String strPath = ",webapps,files," + moduleName + "," + username;

// 解析出文件存放路徑位置
String filepath = System.getProperty("catalina.base") + strPath.replace(',', File.separatorChar);

log.debug("文件上傳路勁位置-------->>>>>>>>>>>>" + filepath);

// 轉換request,解析出request中的文件
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

// 獲取文件map集合
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

String fileName = null;

// 循環遍歷,取出單個文件
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {

// 獲取單個文件
MultipartFile mf = entity.getValue();

// 獲得原始文件名
fileName = mf.getOriginalFilename();

// 截取文件類型; 這里可以根據文件類型進行判斷
String fileType = fileName.substring(fileName.lastIndexOf('.'));

try {
// 截取上傳的文件名稱
String newFileName = fileName.substring(0, fileName.lastIndexOf('.'));

log.debug("上傳來的文件名稱------->>>>>>>>>" + newFileName);

// 拼接上傳文件位置
String newfilePath = filepath + File.separatorChar + newFileName + fileType;

log.debug("拼接好的文件路徑地址------------->>>>>>>>" + newfilePath);

// 重新組裝文件路徑,用於保存在list集合中
String filepathUrl = "files" + File.separatorChar + moduleName + File.separatorChar + username
+ File.separatorChar + newFileName + fileType;

log.debug("文件位置---------------->>>>>>>>>>" + filepathUrl);

// 創建文件存放路徑實例
File dest = new File(filepath);

// 判斷文件夾不存在就創建
if (!dest.exists()) {
dest.mkdirs();
}

// 創建文件實例
File uploadFile = new File(newfilePath);

// 判斷文件已經存在,則刪除該文件
if (uploadFile.exists()) {
uploadFile.delete();
}

log.debug("start upload file-------------->>>>>>> " + fileName);

// 利於spring中的FileCopyUtils.copy()將文件復制
FileCopyUtils.copy(mf.getBytes(), uploadFile);

// 將文件路徑存入list集合中
filePathList.add(filepathUrl);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

log.error("upload failed. filename: " + fileName+"---->>>error message ----->>>>> "+ e.getMessage());

return null;
}
}

return filePathList;
}
}

編寫文件上傳controller控制器

/**
* 單個、批量文件上傳
*
* @param request
* @param response
* @param session
* @param module
* 獲取傳入的模塊名稱
* @return
*/
@RequestMapping(value = "/secure/upload-file/{module}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public String uploadFiles(Model model,HttpServletRequest request, HttpSession session,
@PathVariable("module") String module) {

// 獲取session中保存的用戶信息
User user = (User) session.getAttribute("user");

// 創建list集合用於獲取文件上傳返回路徑名
List<String> list = new ArrayList<String>();

try {

// 獲取上傳完文件返回的路徑,判斷module模塊名稱是否為空,如果為空則給default作為文件夾名
list = FileUploadUtil.uploadFile(request, user.getUsername(),
(module == null || module.length() == 0) ? "default" : module);
// model屬性也行
model.addAttribute("fileUrlList", list);

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
LOG.error("上傳文件發生錯誤=》》" + e.getMessage());

}
// 轉發到uploadTest.jsp頁面
return "uploadTest";
}

/**
* 跳轉至文件上傳頁面
*
* @return
*/
@RequestMapping(value = "/common/upload-page", method = RequestMethod.GET)
public String uploadTestPage() {

return "uploadTest";
}

編寫文件上傳uploadTest.jsp頁面

這里使用兩種方式上傳圖片,ajax上傳用戶體驗更好,可以給出相應的提示給用戶

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript"
src="<%=basePath%>statics/js/jquery/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
var util = {
basePath : function basePath() {// 返回項目路徑
var context = document.getElementsByTagName('base')[0].href;
return context;
},
file_upload : function file_upload() {

// 創建表單數據對象
var obj = new FormData();

// 獲取文件框中的數據
var file1 = document.getElementById("file1").files[0];
var file2 = document.getElementById("file2").files[0];

// 將文件數據添加至表單數據對象中
obj.append("file1", file1);
obj.append("file2", file2);

console.log("請求參數---》》》" + obj);

// 使用ajax異步文件上傳
$.ajax({
url : util.basePath() + 'secure/upload-file/uploadDemo',
type : 'POST',
data : obj,
contentType : false,
processData : false,
mimeType : 'multipart/form-data',
success : function(data) {

console.log(data);
}
})
}

}
</script>
</head>
<body>
<!-- 使用post表單提交,設置類型為:multipart/form-data -->
<form action="<%=basePath%>secure/upload-file/uploadDemo"
enctype="multipart/form-data" method="POST">
<h2>基本form表單上傳文件</h2>
文件一:<input type="file" name="file1" /><br /> 文件二:<input type="file"
name="file2" /><br /> <input type="submit" value="提交" />
</form>


<!-- 使用ajax上傳文件方式 -->
<div>
<h3>ajax上傳文件</h3>
文件一:<input type="file" id="file1" /><br /> 文件二:<input type="file"
id="file2" /><br /> <input type="button"
onclick="util.file_upload()" value="上傳提交">
</div>

<!-- 循環遍歷出圖片 -->
<c:forEach items="${fileUrlList}" var="item">
<img style="width:200px;height:200px" src="http://localhost:8080/${item}">
</c:forEach>
</body>
</html>

ajax方式可以自己更改,根據使用情況修改,控制器這里為了方便查看效果,所以返回的是jsp頁面,
實際使用情況為返回數據,給予前台上傳文件后的提示,將圖片即時顯示在頁面上

運行效果如下:
form表單上傳文件效果圖----》》》》

上傳圖片后返回效果

ajax上傳文件效果圖,這里可以看見console瀏覽器控制台輸出的數據-------》》》》》

ajax上傳文件效果

SpringMVC 上傳文件就總結到這里,有問題可以詢問qq:1119047192,如果你有更好的方式,可以一起討論,希望
可以幫助到大家


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM