文件上傳:
記得前一段時間,為了研究Ajax文件上傳,找了很多資料,在網(wǎng)上看到的大部分是form表單的方式提交文件,對于Ajax方式提交文件并且也要提交表單中其他數(shù)據(jù),發(fā)現(xiàn)提及的并不是很多,后來在同事的幫助下,使用ajaxfileupload最終完成了文件上傳與其他提交的操作,現(xiàn)在分享給大家,希望大家能有有所幫助。
操作步驟:
1 導(dǎo)入jar包:
我們在使用文件上傳時,需要使用到兩個jar包,分別是commons-io與commons-fileupload,在這里我使用的兩個版本分別是2.4與1.3.1版本的,需要使用JS文件與jar包最后會發(fā)給大家一個連接(如何失效請直接我給留言,我會及時更改,謝謝)。
2 修改配置文件:
當(dāng)我們導(dǎo)入的jar包是不夠的,我們需要使用到這些jar包,由于我當(dāng)時使用的是SSM框架,所以我是在application-content.xml中配置一下CommonsMultipartResolver,具體配置方法如下:
1
2
3
4
5
6
7
8
|
<bean id= "multipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" > <property name= "maxUploadSize" > <value> 104857600 </value> </property> <property name= "maxInMemorySize" > <value> 4096 </value> </property> </bean> |
3 JSP文件:
大家對form表單提交問價的方式很熟悉,但是我們有很多情況下并不能直接使用form表單方式直接提交。這時候我們就需要使用Ajax方式提交,Ajax有很多的好處,比如當(dāng)我們不需要刷新頁面獲希望進(jìn)行局部刷新的時候,我們就可以使用Ajax。下面是我的表單提交的JSP頁面,其中包含JS的詳細(xì)步驟和HTML文件:
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
|
<%@ page language= "java" contentType= "text/html; charset=GBK" pageEncoding= "GBK" %> <% @taglib prefix= "c" uri= "http://java.sun.com/jsp/jstl/core" %> <%@ include file= "../commons/taglibs.jsp" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=GBK" > <meta name= "renderer" content= "webkit" > <meta http-equiv= "X-UA-Compatible" content= "IE=edge,chrome=1" > <title>發(fā)布資訊</title> <script type= "text/javascript" src= "${ctx}/resources/new_js/jquery.js" ></script> <script type= "text/javascript" src= "${ctx}/resources/js/ajaxfileupload.js" ></script> <script type= "text/javascript" > function save(){ var typeId = $( "#type_span_info" ).attr( "data-id" ); if (typeof (typeId) == "undefined" ) { $( "#type_p_info" ).show(); return ; } else { $( "#type_p_info" ).hide(); } var target='_blank'>圖片" /> <input type= "text" id= "issue_input_text" class = "issue_text" /> <input type= "file" id= "file" name= "file" class = "issue_file" onchange= "javaScript:validate_img(this)" /> </td> </tr> </tbody> </table> </form> </div> <div class = "financial_pro_icon" > <div class = "financial_pro_icon_l issue_btn1" > <a href= "javaScript:save();" >發(fā)布</a> </div> <div class = "financial_pro_icon_r issue_btn1" > <a href= "${ctx}/info/gotoInfo?index=2" >取消</a> </div> </div> </div> </div> </div> </div> </div> </div> <!--頁面主體 end--> </div> </body> </html> |
上面的代碼是我在項目實際開發(fā)的過程中所用的代碼,具體的CSS文件與JS文件我已經(jīng)刪掉了,但是不會影響具體的操作,大家使用的時候只需要把其中的class文件刪掉了就可以了。好了,我們在說一說上面的代碼。首先為大家解釋一下ctx的作用,在我們項目開發(fā)的過程中,我們要求必須使用絕對路徑,所有{ctx}是我們封裝好的一個東西,就是我們的服務(wù)器地址+端口號+項目名稱。當(dāng)我們使用的時候,只需要引用一下文件,就是上面直接使用的<%@ include file=”../commons/taglibs.jsp”%>,當(dāng)我們用的時候直接使用${ctx}就可以,大家在使用的時候就直接使用自己的本機(jī)地址端口號與項目名稱就可以。后面的/resources/new_js/jquery.js就是我們要使用的jqery.js文件的存放地址。
其實在上面的Ajax的操作中,我相當(dāng)于做了兩次的Ajax的提價,但是在第一次提交的時候,后臺給我們返回一個參數(shù),就是我們的文件存放路徑與文件名稱,在第二次提交的時候,我們將這些參數(shù)與其他參數(shù)同時上傳到后臺,并將這些參數(shù)保存到數(shù)據(jù)庫中,以便我們使用。
* 4 后臺代碼:
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
|
//文件上傳 @RequestMapping (value = "/doUpload" , method = RequestMethod.POST, produces = "text/html; charset=UTF-8" ) @ResponseBody public String doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException { List<String> fileNames = null ; if (request instanceof MultipartHttpServletRequest) { // process the uploaded file logger.info( "=====進(jìn)入文件類型選擇=====" ); fileNames = uploadAttachment(request, "file" ); } String url = "" ; if (fileNames.size() > 0 ) { for ( int i = 0 ; i < fileNames.size(); i++) { url = url + fileNames.get(i); if (i < fileNames.size() - 1 ){ url = url + "," ; } } } return url; } //文件上傳的工具類 public List<String> uploadAttachment(HttpServletRequest request, String type) throws IOException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; List<MultipartFile> files = multipartRequest.getFiles(type); logger.info( "數(shù)據(jù)長度========>>>>>>>>>>" + files.size()); Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); int month = now.get(Calendar.MONTH) + 1 ; String realPath = PropertiesUtil.getProperty( "realPath" ); System.err.println( "realpath=====>>>>>" + realPath); //String savePath = request.getSession().getServletContext().getRealPath("/") + "p_image\" + type + "\" + year+ "\" + month + "\"; String savePath = "government" + File.separator + "image" + File.separator + year+ File.separator + month + File.separator; logger.info( "保存路徑=====>" + savePath); List<String> fileNames = new ArrayList<String>(); for (MultipartFile multipartFile : files) { logger.info( "--" + multipartFile.getOriginalFilename()); String fileName = multipartFile.getOriginalFilename(); String prefix = fileName.substring(fileName.lastIndexOf( "." ) + 1 ); String custName = "" + System.currentTimeMillis() + "." + prefix; if (UsedUtil.isNotNull(fileName)) { File targetFile = new File(realPath+savePath, custName); // fileName = year+"-"+month+"-"+fileName; if (!targetFile.exists()) { targetFile.mkdirs(); multipartFile.transferTo(targetFile); } try { } catch (Exception e) { e.printStackTrace(); } fileNames.add(savePath + custName); } } return fileNames; } //添加咨詢 @RequestMapping (value = "/addInfo" , method = RequestMethod.POST) @ResponseBody public Integer addInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileUrl) { InfoBean bean = new InfoBean(); if (UsedUtil.isNotNull(fileUrl)){ bean.setImagePath(fileUrl); } Map<String, Object> paramMap = ControllerUtil.request2Map(request); bean.setTitle((String) paramMap.get( "title" )); bean.setSummary((String) paramMap.get( "summary" )); bean.setContent((String) paramMap.get( "content" )); bean.setTypeId((String)paramMap.get( "typeId" )); return infoService.insInfo(bean); } |
在上面的代碼中我們可以看到,在文件第一次上傳的過程中,我們首先進(jìn)入到doUpload中,然后使用uploadAttachment工具類,并將文件上傳到服務(wù)器中,在上傳的過程中,我首先做了一個文件唯一名稱的操作,就是獲取當(dāng)前時間的毫秒數(shù),雖然不能絕對保證,但是到并發(fā)量小的時候可以保證不會造成文件名稱重復(fù)。然后,我將文件上傳的路徑的上傳地址寫到了.properties中,這樣的好處是當(dāng)我們想更換文件上傳的路徑時,我們就可以直接修改.properties文件,而讀取.properties文件的具體方式在我的另一篇文章中講到。最后,我們在開發(fā)的過程中,文件保存一般是保存到文件服務(wù)器中,而文件服務(wù)器一般是在Linux中,而在不同的服務(wù)器中,路徑是使用斜杠還是反斜杠是不同的,所有我在這里面使用了File.separator來代替,F(xiàn)ile.separator在不同的系統(tǒng)中可以自動生成斜杠獲反斜杠。
以上所述是小編給大家介紹的使用Ajax進(jìn)行文件與其他參數(shù)的上傳功能(java開發(fā)),希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的,在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://blog.csdn.net/hhb1san14/article/details/54192341