利用SpringMVC和Ajax實(shí)現(xiàn)文件上傳功能
個(gè)人根據(jù)相關(guān)資料實(shí)現(xiàn)利用SpringMVC和Ajax實(shí)現(xiàn)文件上傳功能:
環(huán)境:
1.JDK1.7
2.maven3.3.9
3.Tomcat7
第一步:
導(dǎo)入相關(guān)jar包:

第二步:
配置springmvc-config.xml
<?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: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">
<context:component-scan base-package="com.lc" />
<!-- 配置視圖解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上傳文件的最大大小 -->
<property name="maxUploadSize" value="17367648787"></property>
<!-- 上傳文件的編碼 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
</beans>
第三步:
配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>fileupload</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!--Springmvc的控制分發(fā)器 --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
第四步:
新建一個(gè)Controller類(lèi),并實(shí)現(xiàn)文件上傳的功能
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.json.Json;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
@Controller
public class FileUploadController {
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file,
HttpServletRequest request) {
Map<String, String> modelMap = new HashMap<>();
if (!file.isEmpty()) {
String storePath = "E://images";
Random r = new Random();
String fileName = file.getOriginalFilename();
String[] split = fileName.split(".jpg");
fileName = split[0] + r.nextInt(1000);
fileName = fileName + ".jpg";
File filePath = new File(storePath, fileName);
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();// 如果目錄不存在,則創(chuàng)建目錄
}
try {
file.transferTo(new File(storePath + File.separator + fileName));// 把文件寫(xiě)入目標(biāo)文件地址
} catch (Exception e) {
e.printStackTrace();
modelMap.put("back", "error");
String json = JSON.toJSONString(modelMap);
return json;
}
modelMap.put("back", "success");
} else {
modelMap.put("back", "error");
}
String json = JSON.toJSONString(modelMap);
return json;
}
}
第五步:
在WEB-INF下,新建一個(gè)pages文件夾,并創(chuàng)建實(shí)現(xiàn)文件上傳的jsp或者HTML文件(我使用的是jsp):

在index.jsp下寫(xiě)入相關(guān)的ajax的方法,在使用ajax之前必須先導(dǎo)入js庫(kù)。
<body>
<form id="uploadForm" enctype="multipart/form-data" method="post">
<input type="file" name="file">
</form>
<br>
<input type="button" id="upload" value="上傳">
</body>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#upload').click(function() {
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
type : 'POST',
url : 'upload',
data : formData,
cache : false,
processData : false,
contentType : false,
}).success(function(data) {
var result = JSON.parse(data);
alert(result.back);
}).error(function() {
alert("上傳失敗");
});
});
});
</script>
第六步:
進(jìn)行測(cè)試

上傳文件

上傳成功

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringMVC使用第三方組件實(shí)現(xiàn)文件上傳
- SpringMVC文件上傳原理及實(shí)現(xiàn)過(guò)程解析
- ssm框架Springmvc文件上傳實(shí)現(xiàn)代碼詳解
- Ajax實(shí)現(xiàn)文件上傳功能(Spring MVC)
- SpringMVC 上傳文件 MultipartFile 轉(zhuǎn)為 File的方法
- SpringMVC上傳文件并保存到本地代碼實(shí)例
- SpringMVC實(shí)現(xiàn)多文件上傳
- SpringMVC 單文件,多文件上傳實(shí)現(xiàn)詳解
- Springmvc文件上傳實(shí)現(xiàn)流程解析
相關(guān)文章
Java代碼執(zhí)行順序——類(lèi)的初始化場(chǎng)景
這篇文章主要為大家介紹了Java代碼執(zhí)行順序類(lèi)的初始化場(chǎng)景實(shí)例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
PostMan如何傳參給@RequestBody(接受前端參數(shù))
這篇文章主要介紹了PostMan如何傳參給@RequestBody(接受前端參數(shù)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
詳解XML,Object,Json轉(zhuǎn)換與Xstream的使用
這篇文章主要介紹了詳解XML,Object,Json轉(zhuǎn)換與Xstream的使用的相關(guān)資料,需要的朋友可以參考下2017-02-02
手把手教你用Java實(shí)現(xiàn)一套簡(jiǎn)單的鑒權(quán)服務(wù)
現(xiàn)今大部分系統(tǒng)都會(huì)有自己的鑒權(quán)服務(wù),本文介紹了最常用的鑒權(quán)服務(wù),就是日常用戶的登錄登出,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
帶你走進(jìn)Maven的大門(mén)-最全Maven配置及集成idea工具總結(jié)
Maven項(xiàng)目對(duì)象模型(POM),是一個(gè)項(xiàng)目管理工具可以通過(guò)一小段描述信息來(lái)管理項(xiàng)目的構(gòu)建,報(bào)告和文檔的軟件.那我們想要在IDEA中使用Maven得進(jìn)行一些配置,接下來(lái)我們具體看一下是如何配置使用的,需要的朋友可以參考下2021-06-06
maven中profile動(dòng)態(tài)打包不同環(huán)境配置文件的實(shí)現(xiàn)
開(kāi)發(fā)項(xiàng)目時(shí)會(huì)遇到這個(gè)問(wèn)題:開(kāi)發(fā)環(huán)境,測(cè)試環(huán)境,生產(chǎn)環(huán)境的配置文件不同, 打包時(shí)經(jīng)常要手動(dòng)更改配置文件,本文就來(lái)介紹一下maven中profile動(dòng)態(tài)打包不同環(huán)境配置文件的實(shí)現(xiàn),感興趣的可以了解一下2023-10-10

