异步上传&预览图片-不压缩图片

本例使用ajaxFileUpload异步上传预览图片

1 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
2         <property name="maxUploadSize">
3             <value>10485760000</value>
4         </property>
5         <property name="maxInMemorySize">
6             <value>4096</value>
7         </property>
8     </bean>
springmvc.xml
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <title>HTML5上传图片预览</title>
 5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 6 <script src="http://www.codefans.net/ajaxjs/jquery-1.6.2.min.js"></script>
 7 <script src="./ajaxfileupload.js"></script>
 8 </head>
 9 <body>
10 <h3>请选择图片文件:JPG/GIF</h3>
11 
12 <input type="button"  onclick="uploadImages('file0')" value="上传"/>
13 <form name="form0" id="form0" >
14 <input type="file" name="file0" id="file0" multiple="multiple" /><br><img src="" id="img0" >
15 
16 </form>
17 <script>    
18 $("#file0").change(function(){
19     var objUrl = getObjectURL(this.files[0]) ;
20     if (objUrl) {
21         $("#img0").attr("src", objUrl) ;
22     }
23 }) ;
24 //建立一個可存取到該file的url
25 function getObjectURL(file) {
26     var url = null ; 
27     if (window.createObjectURL!=undefined) { // basic
28         url = window.createObjectURL(file) ;
29     } else if (window.URL!=undefined) { // mozilla(firefox)
30         url = window.URL.createObjectURL(file) ;
31     } else if (window.webkitURL!=undefined) { // webkit or chrome
32         url = window.webkitURL.createObjectURL(file) ;
33     }
34     return url ;
35 }
36 function uploadImages(type) {
37     ajax_upload(type,type,function(data) { //function(data)是上传图片的成功后的回调方法
38             var isrc = data.relatPath.replace(/\/\//g, '/'); //获取的图片的绝对路径
39             console.log(isrc) //给<input>的src赋值去显示图片
40         });
41 }
42 
43 function ajax_upload(type,feid, callback) { //具体的上传图片方法
44         if (image_check(feid)) { //自己添加的文件后缀名的验证
45             $.ajaxFileUpload({
46                 fileElementId: feid,    //需要上传的文件域的ID,即<input type="file">的ID。
47                 url: 'http://****/upload.htm?updateP='+type, //后台方法的路径
48                 type: 'post',   //当要提交自定义参数时,这个参数要设置成post
49                 dataType: 'json',   //服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
50                 secureuri: false,   //是否启用安全提交,默认为false。
51                 async : true,   //是否是异步
52                 success: function(data) {   //提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
53                     if (callback) callback.call(this, data);
54                 },
55                 error: function(data, status, e) {  //提交失败自动执行的处理函数。
56                     console.error(e);
57                 }
58             });
59         }
60     }
61     function image_check(feid) { //自己添加的文件后缀名的验证
62         var img = document.getElementById(feid);
63         return /.(jpg|png|gif|bmp)$/.test(img.value)?true:(function() {
64             modals.info('图片格式仅支持jpg、png、gif、bmp格式,且区分大小写。');
65             return false;
66         })();
67     }
68 </script>
69 </body>
70 </html>
up.html
  1 jQuery.extend({
  2     
  3 
  4     createUploadIframe: function(id, uri)
  5     {
  6             //create frame
  7             var frameId = 'jUploadFrame' + id;
  8             var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
  9             if(window.ActiveXObject)
 10             {
 11                 if(typeof uri== 'boolean'){
 12                     iframeHtml += ' src="' + 'javascript:false' + '"';
 13 
 14                 }
 15                 else if(typeof uri== 'string'){
 16                     iframeHtml += ' src="' + uri + '"';
 17 
 18                 }    
 19             }
 20             iframeHtml += ' />';
 21             jQuery(iframeHtml).appendTo(document.body);
 22 
 23             return jQuery('#' + frameId).get(0);            
 24     },
 25     createUploadForm: function(id, fileElementId, data)
 26     {
 27         //create form    
 28         var formId = 'jUploadForm' + id;
 29         var fileId = 'jUploadFile' + id;
 30         var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');    
 31         if(data)
 32         {
 33             for(var i in data)
 34             {
 35                 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
 36             }            
 37         }        
 38         var oldElement = jQuery('#' + fileElementId);
 39         var newElement = jQuery(oldElement).clone();
 40         jQuery(oldElement).attr('id', fileId);
 41         jQuery(oldElement).before(newElement);
 42         jQuery(oldElement).appendTo(form);
 43 
 44 
 45         
 46         //set attributes
 47         jQuery(form).css('position', 'absolute');
 48         jQuery(form).css('top', '-1200px');
 49         jQuery(form).css('left', '-1200px');
 50         jQuery(form).appendTo('body');        
 51         return form;
 52     },
 53 
 54     ajaxFileUpload: function(s) {
 55         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout        
 56         s = jQuery.extend({}, jQuery.ajaxSettings, s);
 57         var id = new Date().getTime()        
 58         var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
 59         var io = jQuery.createUploadIframe(id, s.secureuri);
 60         var frameId = 'jUploadFrame' + id;
 61         var formId = 'jUploadForm' + id;        
 62         // Watch for a new set of requests
 63         if ( s.global && ! jQuery.active++ )
 64         {
 65             jQuery.event.trigger( "ajaxStart" );
 66         }            
 67         var requestDone = false;
 68         // Create the request object
 69         var xml = {}   
 70         if ( s.global )
 71             jQuery.event.trigger("ajaxSend", [xml, s]);
 72         // Wait for a response to come back
 73         var uploadCallback = function(isTimeout)
 74         {            
 75             var io = document.getElementById(frameId);
 76             try 
 77             {                
 78                 if(io.contentWindow)
 79                 {
 80                      xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
 81                      xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
 82                      
 83                 }else if(io.contentDocument)
 84                 {
 85                      xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
 86                     xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
 87                 }                        
 88             }catch(e)
 89             {
 90                 jQuery.handleError(s, xml, null, e);
 91             }
 92             if ( xml || isTimeout == "timeout") 
 93             {                
 94                 requestDone = true;
 95                 var status;
 96                 try {
 97                     status = isTimeout != "timeout" ? "success" : "error";
 98                     // Make sure that the request was successful or notmodified
 99                     if ( status != "error" )
100                     {
101                         // process the data (runs the xml through httpData regardless of callback)
102                         var data = jQuery.uploadHttpData( xml, s.dataType );
103                         // If a local callback was specified, fire it and pass it the data
104 
105                         if ( s.success ) {
106                             s.success( data, status );
107                         }
108 
109                         // Fire the global callback
110                         if( s.global )
111                             jQuery.event.trigger( "ajaxSuccess", [xml, s] );
112                     } else
113                         jQuery.handleError(s, xml, status);
114                 } catch(e)
115                 {
116                     status = "error";
117                     jQuery.handleError(s, xml, status, e);
118                 }
119 
120                 // The request was completed
121                 if( s.global )
122                     jQuery.event.trigger( "ajaxComplete", [xml, s] );
123 
124                 // Handle the global AJAX counter
125                 if ( s.global && ! --jQuery.active )
126                     jQuery.event.trigger( "ajaxStop" );
127 
128                 // Process result
129                 if ( s.complete )
130                     s.complete(xml, status);
131 
132                 jQuery(io).unbind()
133 
134                 setTimeout(function()
135                                     {    try 
136                                         {
137                                             jQuery(io).remove();
138                                             jQuery(form).remove();    
139                                             
140                                         } catch(e) 
141                                         {
142                                             jQuery.handleError(s, xml, null, e);
143                                         }                                    
144 
145                                     }, 100)
146 
147                 xml = null
148 
149             }
150         }
151         // Timeout checker
152         if ( s.timeout > 0 ) 
153         {
154             setTimeout(function(){
155                 // Check to see if the request is still happening
156                 if( !requestDone ) uploadCallback( "timeout" );
157             }, s.timeout);
158         }
159         try 
160         {
161 
162             var form = jQuery('#' + formId);
163             jQuery(form).attr('action', s.url);
164             jQuery(form).attr('method', 'POST');
165             jQuery(form).attr('target', frameId);
166             if(form.encoding)
167             {
168                 jQuery(form).attr('encoding', 'multipart/form-data');                  
169             }
170             else
171             {    
172                 jQuery(form).attr('enctype', 'multipart/form-data');            
173             }            
174             jQuery(form).submit();
175 
176         } catch(e) 
177         {            
178             jQuery.handleError(s, xml, null, e);
179         }
180         
181         jQuery('#' + frameId).load(uploadCallback    );
182         return {abort: function () {}};    
183 
184     },
185 
186     uploadHttpData: function( r, type ) {
187         var data = !type;
188         data = type == "xml" || data ? r.responseXML : r.responseText;
189         // If the type is "script", eval it in global context
190         if ( type == "script" )
191             jQuery.globalEval( data );
192         // Get the JavaScript object, if JSON is used.
193         if ( type == "json" ) {
194             //chrome含style,firefox不含
195             data = r.responseText;    
196             var start = data.indexOf(">");    
197             if(start != -1) {    
198               var end = data.indexOf("<", start + 1);    
199               if(end != -1) {    
200                 data = data.substring(start + 1, end);    
201                }    
202             } 
203             eval( "data = " + data );
204         }
205         // evaluate scripts within html
206         if ( type == "html" )
207             jQuery("<div>").html(data).evalScripts();
208 
209         return data;
210     },
211         handleError: function( s, xhr, status, e ){    
212         // If a local callback was specified, fire it    
213         if ( s.error ) {    
214             s.error.call( s.context || s, xhr, status, e );    
215         }    
216     
217         // Fire the global callback    
218         if ( s.global ) {    
219             (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );    
220         } 
221     }
222 })
ajaxfileupload.js
 1 public void upload(HttpServletRequest request,HttpServletResponse response) throws Exception {
 2         String type=request.getParameter("updateP");
 3         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
 4         CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(type);
 5 
 6         String rootDir = request.getRealPath("/");
 7         String relatDir = File.separator+"uploadimg";
 8         //文件夹不存在则创建
 9         File fdir = new File(rootDir+relatDir);
10         if (!fdir.exists()) { 
11             fdir.mkdirs(); 
12         }
13 
14         String oriName = file.getOriginalFilename();
15         String newName = new Date().getTime()+"_"+oriName;
16         File tempFile = new File(fdir.getPath()+File.separator+newName);
17         file.transferTo(tempFile);
18 
19         Map<String, String> result = new HashMap();
20         result.put("oriName", oriName);
21         result.put("realName", tempFile.getName());
22         result.put("relatPath", relatDir+File.separator+newName);
23         sendjson(result, response);
24         //return null;
25     }
26     /**
27      * 发送json
28      * @param pmap 封装数据
29      * @param response
30      */
31     public void sendjson(Map pmap,HttpServletResponse response){
32         String output = JSONObject.toJSONString(pmap);
33         try {
34             response.setContentType("text/html");
35             response.setCharacterEncoding("UTF-8");
36             response.getWriter().print(output);
37         } catch (IOException e) {
38             e.printStackTrace();
39         }
40     }
41     
42 /**
43  * 
44  * @param stream 上传文件流
45  * @param path 保存路径
46  * @param filename 文件名称
47  * @throws IOException
48  */
49 public void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException{      
50     FileOutputStream fs=new FileOutputStream( path + "/"+ filename);
51     byte[] buffer =new byte[1024*1024];
52     int bytesum = 0;
53     int byteread = 0; 
54     while ((byteread=stream.read(buffer))!=-1){
55         bytesum+=byteread;
56         fs.write(buffer,0,byteread);
57         fs.flush();
58     } 
59     fs.close();
60     stream.close();      
61 }
javaCode

 

posted @ 2017-12-25 15:48  RollBack2010  阅读(173)  评论(0编辑  收藏  举报