国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > AJAX > 正文

Ajax配合Spring實現文件上傳功能代碼

2024-09-01 08:27:15
字體:
來源:轉載
供稿:網友

由于項目需要,開發一個可以上傳圖片到服務器的web表單頁面。

一、 需求

Web表單頁面,可以通過表單上傳圖片以及其他文字信息。

二、 圖片上傳的流程

之前沒有做過這類頁面,通過查詢資料。發現比較常見的做法,是先將圖片上傳到服務器端的某個文件目錄下,服務器向前臺返回圖片的存儲路徑;之后,前臺將圖片存儲路徑以及其他表單信息一起提交到服務器,所有的表單信息存儲在數據庫中。

三、 方法

由于項目需要,我這里介紹兩種圖片上傳方法,第一種是使用ajax對一個圖片直接上傳;第二種是先在前臺將圖片切割為較小的文件,之后使用ajax分別上傳圖片到服務器,服務器實現對文件的拼接。(方法二適合較大文件的上傳)下面我分別對兩種方法做介紹。

方法一: 直接上傳

1 html頁面

<pre name="code" class="html"><!DOCTYPE html> <head></head> <body> <form id="uploadForm" action="/PicSubmit/form" method="post" enctype="multipart/form-data" onsubmit="return submit_check()" class="bootstrap-frm" ></pre><pre name="code" class="html"><input id = "sid" type = "text" name="name" /></pre><pre name="code" class="html"><pre name="code" class="html"><input id = "fileImage" type = "file" name="filename" /></pre><pre name="code" class="html"><input id = "addressid" type = "hidden" name="address" /></pre><pre name="code" class="html"><input id="ajaxsub" type="button" class="button" value="上傳圖片" onclick="fileUpload()<span style="font-family: Arial, Helvetica, sans-serif;">" /> </span></pre><pre name="code" class="html"><input type="submit" class="button" value="提交表單" /> <input type="reset" class="button" value="重置表單" /> </pre></body></html><p></p> <pre></pre> <br> <pre></pre> 這一部分需要注意的是,form表單的enctype屬性必須設置為“multipart/form-data”,在Html5中,如果需要多張圖片一起上傳,可以在<input type="file"> 標簽中,增加multiple屬性,例如:<input type="file" id= “fileImage” multiple />。<br> <br> <br> <p></p> <p>2 js</p> <p>(1)js使用ajax提供的ajaxfileupload.js庫。這個庫使用起來還是比較方便的,和普通的ajax函數使用方法幾乎相同。首先,需要ajaxfileupload.js庫文件。這里需要注意,我之前在網上下載了一個ajaxfileupload.js文件不能用,浪費了很長時間,我直接把js庫文件粘貼到這里,方便分享。</p> <p></p><pre name="code" class="javascript">// JavaScript Document</pre><pre name="code" class="javascript">// ajax file uplaod jQuery.extend({   createUploadIframe: function(id, uri)   {     //create frame     var frameId = 'jUploadFrame' + id;     if(window.ActiveXObject) {       var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');       if(typeof uri== 'boolean'){         io.src = 'javascript:false';       }       else if(typeof uri== 'string'){         io.src = uri;       }     }     else {       var io = document.createElement('iframe');       io.id = frameId;       io.name = frameId;     }     io.style.position = 'absolute';     io.style.top = '-1000px';     io.style.left = '-1000px';     document.body.appendChild(io);     return io;   },   createUploadForm: function(id, fileElementId)   {     //create form     var formId = 'jUploadForm' + id;     var fileId = 'jUploadFile' + id;     var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');     var oldElement = jQuery('#' + fileElementId);     var newElement = jQuery(oldElement).clone();     jQuery(oldElement).attr('id', fileId);     jQuery(oldElement).before(newElement);     jQuery(oldElement).appendTo(form);     //set attributes     jQuery(form).css('position', 'absolute');     jQuery(form).css('top', '-1200px');     jQuery(form).css('left', '-1200px');     jQuery(form).appendTo('body');     return form;   },   ajaxFileUpload: function(s) {     // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout      s = jQuery.extend({}, jQuery.ajaxSettings, s);     var id = s.fileElementId;     var form = jQuery.createUploadForm(id, s.fileElementId);     var io = jQuery.createUploadIframe(id, s.secureuri);     var frameId = 'jUploadFrame' + id;     var formId = 'jUploadForm' + id;     if( s.global && ! jQuery.active++ )     {       // Watch for a new set of requests       jQuery.event.trigger( "ajaxStart" );     }     var requestDone = false;     // Create the request object     var xml = {};     if( s.global )     {       jQuery.event.trigger("ajaxSend", [xml, s]);     }     var uploadCallback = function(isTimeout)     {       // Wait for a response to come back       var io = document.getElementById(frameId);       try       {         if(io.contentWindow)         {           xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;           xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;         }else if(io.contentDocument)         {           xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;           xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;         }       }catch(e)       {         jQuery.handleError(s, xml, null, e);       }       if( xml || isTimeout == "timeout")       {         requestDone = true;         var status;         try {           status = isTimeout != "timeout" ? "success" : "error";           // Make sure that the request was successful or notmodified           if( status != "error" )           {             // process the data (runs the xml through httpData regardless of callback)             var data = jQuery.uploadHttpData( xml, s.dataType );             if( s.success )             {               // ifa local callback was specified, fire it and pass it the data               s.success( data, status );             };             if( s.global )             {               // Fire the global callback               jQuery.event.trigger( "ajaxSuccess", [xml, s] );             };           } else           {             jQuery.handleError(s, xml, status);           }         } catch(e)         {           status = "error";           jQuery.handleError(s, xml, status, e);         };         if( s.global )         {           // The request was completed           jQuery.event.trigger( "ajaxComplete", [xml, s] );         };         // Handle the global AJAX counter         if(s.global && ! --jQuery.active)         {           jQuery.event.trigger("ajaxStop");         };         if(s.complete)         {           s.complete(xml, status);         } ;         jQuery(io).unbind();         setTimeout(function()         { try         {           jQuery(io).remove();           jQuery(form).remove();         } catch(e)         {           jQuery.handleError(s, xml, null, e);         }         }, 100);         xml = null;       };     }     // Timeout checker     if( s.timeout > 0 )     {       setTimeout(function(){         if( !requestDone )         {           // Check to see ifthe request is still happening           uploadCallback( "timeout" );         }       }, s.timeout);     }     try     {       var form = jQuery('#' + formId);       jQuery(form).attr('action', s.url);       jQuery(form).attr('method', 'POST');       jQuery(form).attr('target', frameId);       if(form.encoding)       {         form.encoding = 'multipart/form-data';       }       else       {         form.enctype = 'multipart/form-data';       }       jQuery(form).submit();     } catch(e)     {       jQuery.handleError(s, xml, null, e);     }     if(window.attachEvent){       document.getElementById(frameId).attachEvent('onload', uploadCallback);     }     else{       document.getElementById(frameId).addEventListener('load', uploadCallback, false);     }     return {abort: function () {}};   },   uploadHttpData: function( r, type ) {     var data = !type;     data = type == "xml" || data ? r.responseXML : r.responseText;     // ifthe type is "script", eval it in global context     if( type == "script" )     {       jQuery.globalEval( data );     }     // Get the JavaScript object, ifJSON is used.     if( type == "json" )     {       eval( "data = " + data );     }     // evaluate scripts within html     if( type == "html" )     {       jQuery("<div>").html(data).evalScripts();     }     return data;   },   handleError: function( s, xhr, status, e )   {     // If a local callback was specified, fire it      if ( s.error ) {       s.error.call( s.context || s, xhr, status, e );     }     // Fire the global callback     if ( s.global ) {       (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );     }   } });</pre><p></p> <p><br> </p>             
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 潜江市| 巩义市| 承德市| 金坛市| 徐闻县| 石林| 盱眙县| 宝鸡市| 天全县| 渭源县| 阿瓦提县| 泸水县| 区。| 大埔县| 光泽县| 三门峡市| 盐亭县| 花垣县| 中宁县| 木兰县| 延安市| 黑山县| 慈利县| 峨边| 罗山县| 万宁市| 炉霍县| 望谟县| 夏河县| 保山市| 克东县| 丰台区| 出国| 博野县| 涿鹿县| 星子县| 武宣县| 若羌县| 抚顺县| 广德县| 康马县|