欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringMVC结合ajaxfileupload实现文件无刷新上传代码

程序员文章站 2024-02-28 14:00:46
jquery没有提供ajax的文件上传,我们可以通过ajaxfileupload实现ajax文件的上传。其实ajaxfileupload文件上传特别的简单。下面就演示一下在...

jquery没有提供ajax的文件上传,我们可以通过ajaxfileupload实现ajax文件的上传。其实ajaxfileupload文件上传特别的简单。下面就演示一下在springmvc中实现ajax的文件上传。

1、后台接收代码

首先在spring的配置文件中添加文件上传配置  

<!-- 文件上传 -->
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver">
<property name="defaultencoding" value="utf-8"/> 
</bean> 

再写文件接收的代码

package com.chinaunicom.jlmssp.controller;

import java.io.file;
import java.io.ioexception;
import java.util.arrays;
import java.util.date;
import java.util.hashmap;

import javax.servlet.servletcontext;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;

import org.apache.commons.fileupload.servlet.servletfileupload;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.multipart.commons.commonsmultipartfile;

import com.chinaunicom.jlmssp.model.dataresponse;
import com.chinaunicom.jlmssp.model.javatojsmsg;
import com.chinaunicom.jlmssp.model.org_userinfo;
import com.chinaunicom.jlmssp.model.repaly_expert_home_page;
import com.chinaunicom.jlmssp.services.replay_expertmanageservice;

/**
 * 项目复制管理子系统
 * 专家云管理
 * @author sunyue
 * @version 0.1
 */
@controller
@requestmapping("/admin/replay_expertmanagecontroller.do")
public class replay_expertmanagecontroller {
  
  private static final hashmap<string, string> typemap = new hashmap<string, string>();

  static {
    typemap.put("image", "gif,jpg,jpeg,png,bmp");
    typemap.put("flash", "swf,flv");
    typemap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
    typemap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,dwg,pdf");
  }


  @autowired
  replay_expertmanageservice replayexpertmanageservice;
    
    /**
     * @author sunyue
     * @date 2017年2月28日 下午12:49:33
     * @description: 图片上传方法
     * @return message: -1 没有文件上传 0 上传成功 1 上传失败 2 文件超过上传大小 3 文件格式错误 4 上传文件路径非法 5 上传目录没有写权限
     * @return void 返回类型
     */
    @requestmapping(params = "op=getimageupload", method = requestmethod.post)
    public void getimageupload(@requestparam("upload") commonsmultipartfile file,httpservletrequest request,
        httpservletresponse response) {
      if (!file.isempty()) {
        /*servletcontext servletcontext = request.getsession()
            .getservletcontext();
        string uploadpath = servletcontext.getrealpath("/")
            + "images\\replay-expert\\";
        
        string uppathstring = request.getservletpath(); */
        
        //获取项目工作空间下工程路径的方法,将图片保存到工程路径下
        string t=thread.currentthread().getcontextclassloader().getresource("").getpath();
         int num=t.indexof(".metadata");
         string uploadpath=t.substring(1,num).replace('/', '\\')+"jl_mssp_v3_0\\webcontent\\images\\replay-expert\\";
        
        // 文件上传大小
        long filesize = 3 * 1024 * 1024;

        if (file.getsize() > filesize) {
          backinfo(response, false, 2, "");
          return;
        }

        string originalfilename = file.getoriginalfilename();

        string filesuffix = originalfilename.substring(
            originalfilename.lastindexof(".") + 1).tolowercase();
        if (!arrays.aslist(typemap.get("image").split(",")).contains(
            filesuffix)) {
          backinfo(response, false, 3, "");
          return;
        }

        if (!servletfileupload.ismultipartcontent(request)) {
          backinfo(response, false, -1, "");
          return;
        }

        // 检查上传文件的目录
        file uploaddir = new file(uploadpath);
        if (!uploaddir.isdirectory()) {
          if (!uploaddir.mkdir()) {
            backinfo(response, false, 4, "");
            return;
          }
        }

        // 是否有上传的权限
        if (!uploaddir.canwrite()) {
          backinfo(response, false, 5, "");
          return;
        }
        
        //新文件名
        string newname = "";
        /*if(null != filepre){
          newname += filepre;//对应模块上传的文件名前缀
        }*/
        
         newname +=  "test1111" + "." + filesuffix;

        file savefile = new file(uploadpath, newname);

        try {
          file.transferto(savefile);
          backinfo(response, true, 0, newname);
        } catch (exception e) {
          //log.error(e.getmessage(), e);
          backinfo(response, false, 1, "");
          return;
        }
      } else {
        backinfo(response, false, -1, "");
        return;
      }
    }
    
    // 返回信息
    private void backinfo(httpservletresponse response, boolean flag, int message,
        string filename) {
      string json = "";
      if (flag) {
        json = "{ \"status\": \"success";
      } else {
        json = "{ \"status\": \"error";
      }
      json += "\",\"filename\": \"" + filename + "\",\"message\": \"" + message + "\"}";
      try {
        response.setcontenttype("text/html;charset=utf-8");
        response.getwriter().write(json);
      } catch (ioexception e) {
        //log.error(e.getmessage(), e);
      }
    }
}

2、前台接受代码

使用ajaxfileupload时,首先下载ajaxfileupload文件,导入对应的js文件   

<script type="text/javascript" src="js/ajaxfileupload.js"></script>

文件传输字段必须为file类型,如下:

<input type="file" id="file" name="file" onchange="ajaxfileupload();"/>

 其次,处理上传文件:

function ajaxfileupload() {
  $.ajaxfileupload({
    type: "post",
    async: false,
    data: { "op": 'getimageupload'},
    url:"replay_expertmanagecontroller.do",
    datatype: 'json',
    secureuri: false,
    fileelementid: "upload",
    success: function(data, status) {
      if (data.status == "success") {
        //上传成功
        alert("上传照片成功");
      }
      switch(data.message){
       //解析上传状态
        case "0" : //上传成功
              break;
        case "-1" : //上传文件不能为空
             break;
        default: //上传失败
           break;
      }
      return false;
    }/* ,
    error : function (jqxhr, textstatus, errorthrown) {
      //弹出jqxhr对象的信息
      alert(jqxhr.responsetext);
      //alert(jqxhr.status);
      //alert(jqxhr.readystate);
      //alert(jqxhr.statustext);
        //弹出其他两个参数的信息
      //alert(textstatus);
      alert(errorthrown);
      return false;
    } */
  });
}

三、由于网上的ajaxuploadfile文件都是高版本的,这里将改版完全版文件传上,自己使用

jquery.extend({
  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] );
        }
  },
  createuploadiframe: function(id, uri)
  {
 
    var frameid = 'juploadframe' + id;
    
    if(window.activexobject) {
      if(jquery.browser.version=="9.0")
      {
        io = document.createelement('iframe');
        io.id = frameid;
        io.name = frameid;
      }
      else if(jquery.browser.version=="6.0" || jquery.browser.version=="7.0" || jquery.browser.version=="8.0")
      {
      
        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;    
  },
  ajaxupload:function(s,xml){
    //if((fromfiles.nodetype&&!((filelist=fromfiles.files)&&filelist[0].name)))

    var uid = new date().gettime(),idio='juploadframe'+uid,_this=this;
    var jio=$('<iframe name="'+idio+'" id="'+idio+'" style="display:none">').appendto('body');
    var jform=$('<form action="'+s.url+'" target="'+idio+'" method="post" enctype="multipart/form-data"></form>').appendto('body');
    var oldelement = $('#'+s.fileelementid);
    var newelement = $(oldelement).clone();
    $(oldelement).attr('id', 'juploadfile'+uid);
    $(oldelement).before(newelement);
    $(oldelement).appendto(jform);

    this.remove=function()
    {
      if(_this!==null)
      {
        jnewfile.before(joldfile).remove();
        jio.remove();jform.remove();
        _this=null;
      }
    }
    this.onload=function(){
    
      var data=$(jio[0].contentwindow.document.body).text();
  
  
      try{

        if(data!=undefined){
          data = eval('(' + data + ')');
          try {
            
            if (s.success)
              s.success(data, status);
  
            // fire the global callback
            if(s.global)
              jquery.event.trigger("ajaxsuccess", [xml, s]);
            if (s.complete)
              s.complete(data, status);
            xml = null;
           } catch(e)
             {
          
            status = "error";
            jquery.handleerror(s, xml, status, e);
           }

           // the request was completed
           if(s.global)
             jquery.event.trigger( "ajaxcomplete", [xml, s] );
           // handle the global ajax counter
           if (s.global && ! --jquery.active )
             jquery.event.trigger("ajaxstop");

           // process result
   
        }
     }catch(ex){
       alert(ex.message);
     };
    }
    this.start=function(){jform.submit();jio.load(_this.onload);};
    return this;
     
  },
  createuploadform: function(id, url,fileelementid, data)
  {
    //create form  
    var formid = 'juploadform' + id;
    var fileid = 'juploadfile' + id;
    var form = jquery('<form action="'+url+'" method="post" name="' + formid + '" id="' + formid + '" enctype="multipart/form-data"></form>');  
    if(data)
    {
      for(var i in data)
      {
        jquery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendto(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  
    // create the request object
    var xml = {};
    s = jquery.extend({}, jquery.ajaxsettings, s);
    if(window.activexobject){
      var upload = new jquery.ajaxupload(s,xml);
      upload.start();
     
    }else{
    var id = new date().gettime();
    var form = jquery.createuploadform(id,s.url, s.fileelementid, (typeof(s.data)=='undefined'?false:s.data));
    var io = jquery.createuploadiframe(id, s.secureuri);
    var frameid = 'juploadframe' + id;
    var formid = 'juploadform' + id;    
    // watch for a new set of requests
    if ( s.global && ! jquery.active++ )
    {
      jquery.event.trigger( "ajaxstart" );
    }      
    var requestdone = false;
  
    if ( s.global )
      jquery.event.trigger("ajaxsend", [xml, s]);
    // wait for a response to come back
    var uploadcallback = function(istimeout)
    {      
      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 a local callback was specified, fire it and pass it the data
      
            if (s.success)
              s.success(data, status);
  
            // fire the global callback
            if(s.global)
              jquery.event.trigger("ajaxsuccess", [xml, s]);
            if (s.complete)
              s.complete(data, status);
            
          } else
            jquery.handleerror(s, xml, status);
        } catch(e)
        {
          status = "error";
          jquery.handleerror(s, xml, status, e);
        }

        // the request was completed
        if(s.global)
          jquery.event.trigger( "ajaxcomplete", [xml, s] );
        // handle the global ajax counter
        if (s.global && ! --jquery.active )
          jquery.event.trigger("ajaxstop");

        // process result
        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(){
        // check to see if the request is still happening
        if( !requestdone ) 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)
          {
            jquery(form).attr('encoding', 'multipart/form-data');         
          }
          else
          {  
            jquery(form).attr('enctype', 'multipart/form-data');      
          }  
     
          
          jquery(form).submit();
    
        } catch(e)
        {  
          jquery.handleerror(s, xml, null, e);
        }
        
        jquery('#'+ frameid).load(uploadcallback);
        return {abort: function () {}};  
 
    }
  },

  uploadhttpdata: function( r, type ) {
    
    var data = !type;
    data = type == "xml" || data ? r.responsexml : r.responsetext;
    // if the type is "script", eval it in global context
    if ( type == "script" )
      jquery.globaleval( data );
    // get the javascript object, if json is used.
    if ( type == "json" ){
 
      eval( "data = " + $(data).html() );
    }
    // evaluate scripts within html
    if ( type == "html" )
      jquery("<div>").html(data).evalscripts();
 
    return data;
  }
});

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。