当前位置:Gxlcms > JavaScript > Ajax配合Spring实现文件上传功能(图文教程)

Ajax配合Spring实现文件上传功能(图文教程)

时间:2021-07-01 10:21:17 帮助过:5人阅读

最近在开发一个可以上传图片到服务器的web表面页面,下面给大家分享需求和实现思路,需要的的朋友参考下吧

由于项目需要,开发一个可以上传图片到服务器的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("<p>").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)之后调用ajaxfileupload.js库,编写图片上传脚本,这里命名为ajaxfileuplaod_implement.js

输出现问题,在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>

接下来是重点,在Controller中,使用如下方式接受前台穿回来的文件。<br>

其中需要注意的是,如果前端html的input标签中使用了multiple属性,则表示标签支持上传多个图片,则controller的参数列表中,文件的类型使用MultipartFile[],反之,如果没有使用multiple属性,表示上传的是一张图片,则controller使用MultipartFile类型接收。

输出“存储成功”的提示信息,修改后的名称用于给hiden标签复制,hiden标签的内容会在之后随表单中其他信息一起提交到服务端,通过hiden标签,我们就可以知道与表单关联的图片被存储在什么地方。<br> <br> <p></p> <p>最后,图片上传完成后还需要提交表单,这里使用SpringMVC实现一个表单接收功能。这里名为address的参数,存储的就是图片的存储路径。</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>

方法二 前台切割上传(留着后面补充)<p></p>

<p><br> 
</p> 
<link rel="stylesheet" href="http://static.jb51.net/public/res-min/markdown_views.css?v=1.0"> 
           </pre>

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Ajax请求二进制流进行处理(ajax异步下载文件)

基于CORS实现WebApi Ajax 跨域请求解决方法

Django框架如何使用ajax的post方法(图文教程)

以上就是Ajax配合Spring实现文件上传功能(图文教程)的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行