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

首頁(yè) > 開發(fā) > AJAX > 正文

Ajax配合Spring實(shí)現(xiàn)文件上傳功能代碼

2024-09-01 08:30:40
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

由于項(xiàng)目需要,開發(fā)一個(gè)可以上傳圖片到服務(wù)器的web表單頁(yè)面。

一、 需求

Web表單頁(yè)面,可以通過(guò)表單上傳圖片以及其他文字信息。

二、 圖片上傳的流程

之前沒有做過(guò)這類頁(yè)面,通過(guò)查詢資料。發(fā)現(xiàn)比較常見的做法,是先將圖片上傳到服務(wù)器端的某個(gè)文件目錄下,服務(wù)器向前臺(tái)返回圖片的存儲(chǔ)路徑;之后,前臺(tái)將圖片存儲(chǔ)路徑以及其他表單信息一起提交到服務(wù)器,所有的表單信息存儲(chǔ)在數(shù)據(jù)庫(kù)中。

三、 方法

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

方法一: 直接上傳

1 html頁(yè)面

<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屬性必須設(shè)置為“multipart/form-data”,在Html5中,如果需要多張圖片一起上傳,可以在<input type="file"> 標(biāo)簽中,增加multiple屬性,例如:<input type="file" id= “fileImage” multiple />。<br> <br> <br> <p></p> <p>2 js</p> <p>(1)js使用ajax提供的ajaxfileupload.js庫(kù)。這個(gè)庫(kù)使用起來(lái)還是比較方便的,和普通的ajax函數(shù)使用方法幾乎相同。首先,需要ajaxfileupload.js庫(kù)文件。這里需要注意,我之前在網(wǎng)上下載了一個(gè)ajaxfileupload.js文件不能用,浪費(fèi)了很長(zhǎng)時(shí)間,我直接把js庫(kù)文件粘貼到這里,方便分享。</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> 

(2)之后調(diào)用ajaxfileupload.js庫(kù),編寫圖片上傳腳本,這里命名為ajaxfileuplaod_implement.js 

<p></p><pre name="code" class="javascript">function fileUpload() {    var inputObject = $("#fileImage").get(0);   if(inputObject.value == "")   {     alert("清先選擇需要上傳的圖片");     return false;   }   $.ajaxFileUpload({      url: '/PicSubmit/pic', //服務(wù)器端請(qǐng)求地址      secureuri: false, //是否需要安全協(xié)議,一般設(shè)置為false      type: 'post',     fileElementId: 'fileImage', //文件上傳域的ID      dataType: 'text', //返回值類型 一般設(shè)置為json      enctype:'multipart/form-data',//注意一定要有該參數(shù)      success: function (data, status) //服務(wù)器成功響應(yīng)處理函數(shù)      {        data=decodeURI(data);//服務(wù)器端使用urlencode將中文字符編碼,所以這里需要解碼。這樣做的目的是防止中文亂碼       var address = JSON.parse(data);       for(var i=0;i<address.length;i++){         ajaxfile_onSuccess(address[i]); //這里的success回調(diào)函數(shù)可以自己定義,但是有一點(diǎn)需要注意,就是需要把服務(wù)器返回來(lái)的圖片存儲(chǔ)路徑寫入</pre><pre name="code" class="javascript"><span style="white-space:pre">              </span>//hiden標(biāo)簽的value值中,方法見下面的writeHide函數(shù)       }     },      complete: function(xmlHttpRequest)      {<span style="white-space:pre"> </span>//這里將html中的文件上傳標(biāo)簽替換為新的標(biāo)簽,是應(yīng)為我在開發(fā)過(guò)程中發(fā)現(xiàn),當(dāng)ajax執(zhí)行一次上傳操作之后,再使用file標(biāo)簽選擇文件時(shí),標(biāo)簽沒有反應(yīng),</pre><pre name="code" class="javascript"><span style="white-space:pre">   </span>//所以暫時(shí)使用了這種方法。       inputObject.replaceWith('<input type="file" id="fileImage" name="fileImage" />');     },     error: function (data, status, e)//服務(wù)器響應(yīng)失敗處理函數(shù)     {        //alert("無(wú)法連接到服務(wù)器");     }    })  }</pre><pre name="code" class="javascript"></pre><pre name="code" class="javascript">function writeHide(data){ <span style="white-space:pre"> </span>if($("#addressid").get(0).value == "") <span style="white-space:pre"> </span>{ <span style="white-space:pre">   </span>$("#addressid").get(0).value = data.newName; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>else <span style="white-space:pre"> </span>{ <span style="white-space:pre">   </span>$("#addressid").get(0).value = $("#addressid").get(0).value+","+data.newName; <span style="white-space:pre"> </span>} } </pre><p></p> <p>3 spring.</p> <p>完成上面兩個(gè)部分之后,前臺(tái)的主要工作基本就結(jié)束了。我后臺(tái)使用了spring框架。</p> <p>首先是springMVC的配置文件:viewspace-servlet.xml</p> <p></p><pre name="code" class="html"><?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"     xmlns:mvc="http://www.springframework.org/schema/mvc"     xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd     http://www.springframework.org/schema/mvc      http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd     http://www.springframework.org/schema/context      http://www.springframework.org/schema/context/spring-context-3.1.xsd">   <!-- 靜態(tài)資源 -->   <mvc:resources mapping="/js/**" location="/js/" />   <mvc:resources mapping="/css/**" location="/css/" />   <mvc:resources mapping="/image/**" location="/image/" />   <!-- 掃描web包,應(yīng)用Spring的注解 -->   <context:component-scan base-package="web"/>   <bean id="defaultAnnotationHandlerMapping"      class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />   <bean id="annotationMethodHandlerAdapter"      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />   <!-- 配置視圖解析器,將ModelAndView及字符串解析為具體的頁(yè)面 -->   <bean       class="org.springframework.web.servlet.view.InternalResourceViewResolver"       p:viewClass="org.springframework.web.servlet.view.JstlView"       p:prefix="/WEB-INF/jsp/"       p:suffix=".jsp"/>    <!-- 使springMVC支持圖片上傳 -->    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <!-- 最大上傳尺寸1MB -->       <property name="maxUploadSize" value="10485760"/>       <!-- 默認(rèn)編碼 -->       <property name="defaultEncoding" value="UTF-8" />       <!-- 上傳文件的解析 -->       <property name="resolveLazily" value="true" />   </bean>   <!-- SpringMVC在超出上傳文件限制時(shí),會(huì)拋出org.springframework.web.multipart.MaxUploadSizeExceededException -->    <!-- 該異常是SpringMVC在檢查上傳的文件信息時(shí)拋出來(lái)的,而且此時(shí)還沒有進(jìn)入到Controller方法中 -->    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >      <property name="exceptionMappings">        <props>          <!-- 遇到MaxUploadSizeExceededException異常時(shí),自動(dòng)跳轉(zhuǎn)到/WEB-INF/jsp/error_toobig.jsp頁(yè)面 -->          <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>       </props>     </property>    </bean> </beans></pre>其中,類“org.springframework.web.multipart.commons.CommonsMultipartResolver”的配置是必須的,否則后臺(tái)無(wú)法收到前臺(tái)傳來(lái)的文件。<p></p> <p><br> </p> <p>為了防止文件名中的中文字符傳輸出現(xiàn)問(wèn)題,在web.xml中做如下配置:</p> <p></p><pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">  <context-param>   <param-name>contextConfigLocation</param-name>   <param-value>classpath:applicationContext.xml</param-value>  </context-param>  <listener>   <listener-class>       org.springframework.web.context.ContextLoaderListener     </listener-class>  </listener>  <servlet>   <servlet-name>viewspace</servlet-name>   <servlet-class>       org.springframework.web.servlet.DispatcherServlet     </servlet-class>  </servlet>  <servlet-mapping>   <servlet-name>viewspace</servlet-name>   <url-pattern>/</url-pattern>  </servlet-mapping>  <!-- 支持傳輸中文字符 -->  <filter>      <filter-name>characterEncodingFilter</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>      <init-param>        <param-name>forceEncoding</param-name>        <param-value>true</param-value>      </init-param>    </filter>    <filter-mapping>      <filter-name>characterEncodingFilter</filter-name>      <url-pattern>/*</url-pattern>    </filter-mapping>  </web-app></pre><p></p> <p><br> </p> 

接下來(lái)是重點(diǎn),在Controller中,使用如下方式接受前臺(tái)穿回來(lái)的文件。<br> 

<pre name="code" class="java"> @RequestMapping(value="/pic")   @ResponseBody   public String submitPic(@RequestParam(value = "filename",required = false) MultipartFile[] fileImage,        HttpServletRequest request){     if(fileImage == null){       return "[]";     }     return picSaveService.savePic(fileImage);   }</pre><br> 

其中需要注意的是,如果前端html的input標(biāo)簽中使用了multiple屬性,則表示標(biāo)簽支持上傳多個(gè)圖片,則controller的參數(shù)列表中,文件的類型使用MultipartFile[],反之,如果沒有使用multiple屬性,表示上傳的是一張圖片,則controller使用MultipartFile類型接收。 

<p><br> </p><p>文件接收完成后,就可以對(duì)文件進(jìn)行存儲(chǔ)了,方法有很多,我這里舉一個(gè)例子如下:</p> <p></p><pre name="code" class="java">  public String savePic(MultipartFile[] fileImage){     //為圖片改名     String oldName = "";     String newName = "";     String extension = "";     //圖片按照上傳時(shí)間命名     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");     //存儲(chǔ)每張圖片的信息     List<PicConfirmData> resultList = new ArrayList<PicConfirmData>();     //獲取配置文件中圖片的存儲(chǔ)路徑     String path = Parameters.getInstance().getDatabaseProps().getProperty("pic_save_dir");     //依次將圖片存儲(chǔ)到path路徑下     for(int i=0;i<fileImage.length;i++){       System.out.println(fileImage[i].getOriginalFilename());       oldName = fileImage[i].getOriginalFilename();           extension = oldName.substring(oldName.lastIndexOf("."));       newName = sdf.format(new Date())+extension;       File target = new File(path,newName);       if(!target.exists()){         target.mkdirs();       }       try {           fileImage[i].transferTo(target);         } catch (IllegalStateException e) {           e.printStackTrace();         } catch (IOException e) {           e.printStackTrace();         }       //記錄圖片存儲(chǔ)信息       PicConfirmData pic = null;       try {         //只存名稱,路徑已知,從而節(jié)省數(shù)據(jù)庫(kù)空間         //pic = new PicConfirmData(URLEncoder.encode(oldName, "utf-8"), path+newName);         pic = new PicConfirmData(1,URLEncoder.encode(oldName, "utf-8"), newName);         resultList.add(pic);       } catch (UnsupportedEncodingException e) {         e.printStackTrace();       }     }     return ToolJson.getJsonFromPicConfirmData(resultList);   }</pre>這里將接收到的圖片的原始名稱以及修改后存儲(chǔ)使用的名稱返回給前臺(tái),原始名稱用于在前臺(tái)頁(yè)面輸出“存儲(chǔ)成功”的提示信息,修改后的名稱用于給hiden標(biāo)簽復(fù)制,hiden標(biāo)簽的內(nèi)容會(huì)在之后隨表單中其他信息一起提交到服務(wù)端,通過(guò)hiden標(biāo)簽,我們就可以知道與表單關(guān)聯(lián)的圖片被存儲(chǔ)在什么地方。<br> <br> <p></p> <p>最后,圖片上傳完成后還需要提交表單,這里使用SpringMVC實(shí)現(xiàn)一個(gè)表單接收功能。這里名為address的參數(shù),存儲(chǔ)的就是圖片的存儲(chǔ)路徑。</p> <p></p><pre name="code" class="java">  @RequestMapping(value="/form")   public String submitForm(HttpServletRequest request){     String sid = request.getParameter("name");     String address = request.getParameter("address");          if(sid != null && submiter != null && faultTime != null && message != null && address != null){       if(formDataSaveService.saveForm(sid, submiter, message, address, faultTime)){         return "ac";       }     }     return "error";   }</pre><br> 

方法二  前臺(tái)切割上傳(留著后面補(bǔ)充)<p></p> 

<p><br> </p> <link rel="stylesheet" >            </pre> 

以上所述是小編給大家介紹的Ajax配合Spring實(shí)現(xiàn)文件上傳功能代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 郯城县| 牙克石市| 新疆| 曲水县| 大洼县| 花垣县| 陇西县| 深水埗区| 凤阳县| 察哈| 天门市| 策勒县| 修水县| 左贡县| 确山县| 襄垣县| 韶山市| 栖霞市| 称多县| 十堰市| 广宁县| 望都县| 潮安县| 大足县| 霍山县| 石狮市| 威远县| 龙里县| 洛浦县| 化隆| 冀州市| 洪湖市| 阳高县| 浦县| 伽师县| 呼和浩特市| 股票| 宾川县| 潞西市| 五大连池市| 永善县|