一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語言 - JAVA教程 - SpringMVC結(jié)合ajaxfileupload.js實現(xiàn)文件無刷新上傳

SpringMVC結(jié)合ajaxfileupload.js實現(xiàn)文件無刷新上傳

2020-06-24 11:44玄玉 JAVA教程

這篇文章主要介紹了SpringMVC結(jié)合ajaxfileupload.js實現(xiàn)文件無刷新上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了ajaxfileupload.js實現(xiàn)文件無刷新上傳的具體代碼,供大家參考,具體內(nèi)容如下

直接看代碼吧,注釋都在里面

首先是web.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
 <description>配置SpringMVC的前端控制器</description>
 <servlet-name>upload</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:applicationContext.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>upload</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
 
 <filter>
 <description>解決參數(shù)傳遞過程中的亂碼問題</description>
 <filter-name>CharacterEncodingUTF8</filter-name>
 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
 <init-param>
 <param-name>encoding</param-name>
 <param-value>UTF-8</param-value>
 </init-param>
 </filter>
 <filter-mapping>
 <filter-name>CharacterEncodingUTF8</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>
</web-app>

下面是位于//src//applicationContext.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?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: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-3.2.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 <!-- 啟動Spring的組件自動掃描機(jī)制(Spring會自動掃描base-package指定的包中的類和子包里面類) -->
 <!-- 此處可參考我的文章http://blog.csdn.net/jadyer/article/details/6038604 -->
 <context:component-scan base-package="com.jadyer"/>
 
 <!-- 啟動SpringMVC的注解功能,它會自動注冊HandlerMapping、HandlerAdapter、ExceptionResolver的相關(guān)實例 -->
 <mvc:annotation-driven/>
 
 <!-- 由于web.xml中設(shè)置SpringMVC攔截所有請求,所以在讀取靜態(tài)資源文件時就會讀不到 -->
 <!-- 通過此配置即可指定所有請求或引用"/js/**"的資源,都會從"/js/"中查找 -->
 <mvc:resources mapping="/js/**" location="/js/"/>
 <mvc:resources mapping="/upload/**" location="/upload/"/>
 
 <!-- SpringMVC上傳文件時,需配置MultipartResolver處理器 -->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 <!-- 指定所上傳文件的總大小不能超過800KB......注意maxUploadSize屬性的限制不是針對單個文件,而是所有文件的容量之和 -->
 <property name="maxUploadSize" value="800000"/>
 </bean>
 
 <!-- SpringMVC在超出上傳文件限制時,會拋出org.springframework.web.multipart.MaxUploadSizeExceededException -->
 <!-- 該異常是SpringMVC在檢查上傳的文件信息時拋出來的,而且此時還沒有進(jìn)入到Controller方法中 -->
 <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
 <property name="exceptionMappings">
 <props>
 <!-- 遇到MaxUploadSizeExceededException異常時,自動跳轉(zhuǎn)到/WEB-INF/jsp/error_fileupload.jsp頁面 -->
 <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
 </props>
 </property>
 </bean>
 
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/jsp/"/>
 <property name="suffix" value=".jsp"/>
 </bean>
</beans>

下面是上傳文件內(nèi)容過大時的提示頁面//WEB-INF//jsp//error_fileupload.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<h1>文件過大,請重新選擇</h1>

下面是用于選擇文件的上傳頁面index.jsp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<%@ page language="java" pageEncoding="UTF-8"%>
<!-- 此處不能簡寫為<script type="text/javascript" src=".."/> -->
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script>
 
<script type="text/javascript">
function ajaxFileUpload(){
 //開始上傳文件時顯示一個圖片,文件上傳完成將圖片隱藏
 //$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();});
 //執(zhí)行上傳文件操作的函數(shù)
 $.ajaxFileUpload({
 //處理文件上傳操作的服務(wù)器端地址(可以傳參數(shù),已親測可用)
 url:'${pageContext.request.contextPath}/test/fileUpload?uname=玄玉',
 secureuri:false,      //是否啟用安全提交,默認(rèn)為false
 fileElementId:'myBlogImage',   //文件選擇框的id屬性
 dataType:'text',      //服務(wù)器返回的格式,可以是json或xml等
 success:function(data, status){  //服務(wù)器響應(yīng)成功時的處理函數(shù)
 data = data.replace("<PRE>", ''); //ajaxFileUpload會對服務(wù)器響應(yīng)回來的text內(nèi)容加上<pre>text</pre>前后綴
 data = data.replace("</PRE>", '');
 data = data.replace("<pre>", '');
 data = data.replace("</pre>", ''); //本例中設(shè)定上傳文件完畢后,服務(wù)端會返回給前臺[0`filepath]
 if(data.substring(0, 1) == 0){  //0表示上傳成功(后跟上傳后的文件路徑),1表示失敗(后跟失敗描述)
 $("img[id='uploadImage']").attr("src", data.substring(2));
 $('#result').html("圖片上傳成功<br/>");
 }else{
 $('#result').html('圖片上傳失敗,請重試!!');
 }
 },
 error:function(data, status, e){ //服務(wù)器響應(yīng)失敗時的處理函數(shù)
 $('#result').html('圖片上傳失敗,請重試!!');
 }
 });
}
</script>
 
<div id="result"></div>
<img id="uploadImage" src="http://www.firefox.com.cn/favicon.ico">
 
<input type="file" id="myBlogImage" name="myfiles"/>
<input type="button" value="上傳圖片" onclick="ajaxFileUpload()"/>
 
<!--
AjaxFileUpload簡介
官網(wǎng):http://phpletter.com/Our-Projects/AjaxFileUpload/
簡介:jQuery插件AjaxFileUpload能夠?qū)崿F(xiàn)無刷新上傳文件,并且簡單易用,它的使用人數(shù)很多,非常值得推薦
注意:引入js的順序(它依賴于jQuery)和頁面中并無表單(只是在按鈕點擊的時候觸發(fā)ajaxFileUpload()方法)
常見錯誤及解決方案如下
1)SyntaxError: missing ; before statement
 --檢查URL路徑是否可以訪問
2)SyntaxError: syntax error
 --檢查處理提交操作的JSP文件是否存在語法錯誤
3)SyntaxError: invalid property id
 --檢查屬性ID是否存在
4)SyntaxError: missing } in XML expression
 --檢查文件域名稱是否一致或不存在
5)其它自定義錯誤
 --可使用變量$error直接打印的方法檢查各參數(shù)是否正確,比起上面這些無效的錯誤提示還是方便很多
 -->

最后是處理文件上傳的FileUploadController.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package com.jadyer.controller;
 
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
 
/**
 * SpringMVC中的文件上傳
 * 1)由于SpringMVC使用的是commons-fileupload實現(xiàn),所以先要將其組件引入項目中
 * 2)在SpringMVC配置文件中配置MultipartResolver處理器(可在此加入對上傳文件的屬性限制)
 * 3)在Controller的方法中添加MultipartFile參數(shù)(該參數(shù)用于接收表單中file組件的內(nèi)容)
 * 4)編寫前臺表單(注意enctype="multipart/form-data"以及<input type="file" name="****"/>)
 * PS:由于這里使用了ajaxfileupload.js實現(xiàn)無刷新上傳,故本例中未使用表單
 * ---------------------------------------------------------------------------------------------
 * 這里用到了如下的jar
 * commons-io-2.4.jar
 * commons-fileupload-1.3.jar
 * commons-logging-1.1.2.jar
 * spring-aop-3.2.4.RELEASE.jar
 * spring-beans-3.2.4.RELEASE.jar
 * spring-context-3.2.4.RELEASE.jar
 * spring-core-3.2.4.RELEASE.jar
 * spring-expression-3.2.4.RELEASE.jar
 * spring-jdbc-3.2.4.RELEASE.jar
 * spring-oxm-3.2.4.RELEASE.jar
 * spring-tx-3.2.4.RELEASE.jar
 * spring-web-3.2.4.RELEASE.jar
 * spring-webmvc-3.2.4.RELEASE.jar
 * ---------------------------------------------------------------------------------------------
 * @create Sep 14, 2013 5:06:09 PM
 * @author 玄玉<http://blog.csdn.net/jadyer>
 */
@Controller
@RequestMapping("/test")
public class FileUploadController {
 /**
 * 這里這里用的是MultipartFile[] myfiles參數(shù),所以前臺就要用<input type="file" name="myfiles"/>
 * 上傳文件完畢后返回給前臺[0`filepath],0表示上傳成功(后跟上傳后的文件路徑),1表示失敗(后跟失敗描述)
 */
 @RequestMapping(value="/fileUpload")
 public String addUser(@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException{
 //可以在上傳文件的同時接收其它參數(shù)
 System.out.println("收到用戶[" + uname + "]的文件上傳請求");
 //如果用的是Tomcat服務(wù)器,則文件會上傳到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夾中
 //這里實現(xiàn)文件上傳操作用的是commons.io.FileUtils類,它會自動判斷/upload是否存在,不存在會自動創(chuàng)建
 String realPath = request.getSession().getServletContext().getRealPath("/upload");
 //設(shè)置響應(yīng)給前臺內(nèi)容的數(shù)據(jù)格式
 response.setContentType("text/plain; charset=UTF-8");
 //設(shè)置響應(yīng)給前臺內(nèi)容的PrintWriter對象
 PrintWriter out = response.getWriter();
 //上傳文件的原名(即上傳前的文件名字)
 String originalFilename = null;
 //如果只是上傳一個文件,則只需要MultipartFile類型接收文件即可,而且無需顯式指定@RequestParam注解
 //如果想上傳多個文件,那么這里就要用MultipartFile[]類型來接收文件,并且要指定@RequestParam注解
 //上傳多個文件時,前臺表單中的所有<input type="file"/>的name都應(yīng)該是myfiles,否則參數(shù)里的myfiles無法獲取到所有上傳的文件
 for(MultipartFile myfile : myfiles){
 if(myfile.isEmpty()){
 out.print("1`請選擇文件后上傳");
 out.flush();
 return null;
 }else{
 originalFilename = myfile.getOriginalFilename();
 System.out.println("文件原名: " + originalFilename);
 System.out.println("文件名稱: " + myfile.getName());
 System.out.println("文件長度: " + myfile.getSize());
 System.out.println("文件類型: " + myfile.getContentType());
 System.out.println("========================================");
 try {
  //這里不必處理IO流關(guān)閉的問題,因為FileUtils.copyInputStreamToFile()方法內(nèi)部會自動把用到的IO流關(guān)掉
  //此處也可以使用Spring提供的MultipartFile.transferTo(File dest)方法實現(xiàn)文件的上傳
  FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, originalFilename));
 } catch (IOException e) {
  System.out.println("文件[" + originalFilename + "]上傳失敗,堆棧軌跡如下");
  e.printStackTrace();
  out.print("1`文件上傳失敗,請重試!!");
  out.flush();
  return null;
 }
 }
 }
 //此時在Windows下輸出的是[D:\Develop\apache-tomcat-6.0.36\webapps\AjaxFileUpload\\upload\憤怒的小鳥.jpg]
 //System.out.println(realPath + "\\" + originalFilename);
 //此時在Windows下輸出的是[/AjaxFileUpload/upload/憤怒的小鳥.jpg]
 //System.out.println(request.getContextPath() + "/upload/" + originalFilename);
 //不推薦返回[realPath + "\\" + originalFilename]的值
 //因為在Windows下<img src="file:///D:/aa.jpg">能被firefox顯示,而<img src="D:/aa.jpg">firefox是不認(rèn)的
 out.print("0`" + request.getContextPath() + "/upload/" + originalFilename);
 out.flush();
 return null;
 }
}
 

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 操碰人人 | 国产高清免费在线 | 香蕉久久一区二区三区 | 成人福利免费在线观看 | 999热在线精品观看全部 | 国产在线视频在线观看 | 欧美在线一二三区 | 国产私人影院 | 免费超级乱淫视频播放性 | 91麻豆国产福利精品 | 久久一本岛在免费线观看2020 | 国产精选之刘婷野战 | 青草色视频| 美女1819xxxx | 欧美一区欧美二区 | 男人的j伸到女人的屁股眼 男人吃奶动态图 | 国产精品久久久久久爽爽爽 | 小早川怜子视频在线观看 | 高清女主播一区二区三区 | 亚洲国产99在线精品一区69堂 | 图片专区亚洲欧美另类 | 天天舔天天操天天干 | 亚洲天堂2015 | 久久久免费热线精品频 | 青青热久久综合网伊人 | 日本动漫打扑克动画片樱花动漫 | 国产最强大片免费视频 | 手机看片国产免费久久网 | 国产美女久久精品香蕉69 | 午夜福到在线4国产 | 黑帮大佬与我的365天2标清中文 | 被巨大黑人的翻白眼 | 美女张开腿让男人桶的 视频 | 亚洲精品卡一卡2卡3卡4卡 | 四虎永久在线精品国产 | 俄罗斯三级在线观看级 | 本站只有精品 | 亚洲精品视频观看 | 亚洲视频中文字幕 | 小小水蜜桃视频高清在线观看免费 | 色播开心网 |