天天看点

uploadify在火狐下上传不了的解决方案,java版(Spring+SpringMVC+MyBatis)详细解决方案



下面我就把我遇到的这些问题现象、以及解决方案和大家分享一下,希望能够帮助大家快速解决java项目中的问题。

错误现象:

在:ie浏览器和谷歌浏览器中,当使用uploadify进行文件上传的时候,是正常的,能够上传成功,当使用火狐浏览器的时候,发现死活也上传不了。没有任何反应,真是气死人啊。

解决方法:

在百度上搜索”uploadify兼容性/uploadify不兼容获取”,发现搜出很多,但仔细看,发现似乎都是一个人写的文章。解释的主要原因是(下面一段摘抄自:http://blog.csdn.net/longlong821/article/details/7785703):

 jquery uploadify在ie下可以正常上传,在实现异步上传的时候,每一个文件在上传时都会提交给服务器一个请求。每个请求都需要安全验证,session和cookie的校验。是的,就是这样。由于jquery uploadify是借助flash来实现上传的,每一次向后台发送数据流请求时,ie会自动把本地cookie存储捆绑在一起发送给服务器。但firefox、chrome不会这样做,他们会认为这样不安全。

session又称为会话状态,是web系统中最常用的状态,用于维护和当前浏览器实例相关的一些信息。举个例子来说,我们可以把已登录用户的用户名放在session中,这样就能通过判断session中的某个key来判断用户是否登录,如果登录的话用户名又是多少。

<script type="text/javascript"> 

$(document).ready(function() { 

    $("#fileupload").uploadify({ 

        'swf' : '/uploadify/scripts/uploadify.swf', 

        'uploader' : '/fileupload;jsessionid=${pagecontext.session.id}', 

        'auto' : true, 

        'multi' : false, 

        'buttontext' : 'browse', 

        'filedesc' : '支持格式:jpg/gif/jpeg/png/bmp.', 

        'fileext' : '*.jpg;*.gif;*.jpeg;*.png;*.bmp', 

        'onuploadsuccess': onuploadsuccess 

    }); 

}); 

</script> 

最关键的就是红字那部份了,要注意的是jsessionid前面那个是个分号而不是问号,写成问号就作为参数传递了

最后在进行搜索,由于uploadify依赖flash,所以建议安装针对火狐的adobeflash插件.

最后编写自己的uploadify上传例子:

1、编写jsessionid获取的例子,在我们项目中,我把它放在了common-session.jsp中,内容如下(这样写的原因是,我们的前后台用的不同的common.jsp,为了前后台都使用同一套的jsessionid,通过<%@ include file="common-session.jsp" %>包含进去,注意:如果不这样做,而是分别在两套common.jsp中写如下的jsessionid的代码,最终发现要么后台能够使用上传;要么前台能够使用上传;或者前台上传一次之后,再去后台上传,发现上传不了了,反之也是同样的效果):

<%@ page iselignored=”false” %>

<%@ page language=”java” pageencoding=”utf-8”%>

<%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c” %>

<%

string sessionid =  session.getid();

%>

<c:set var=”jsessionid” value=”<%=sessionid %>” scope=”session”/>

<script name=”systemjs” type=”text/javascript”>

var jsessionid = ‘${jsessionid}’;

</script>

2、在common.jsp中引入上面的"common-session.jsp

3、编写后台java上传逻辑,这里我是用的是springmvc+spring+mybatis,后台代码如下(关于下面代码,并非我所写,不觉得下面的java代码是规范的,此处允许大家hehe 和吐槽):

package xxxx;

import java.io.file;

import java.io.inputstream;

import java.util.arraylist;

import java.util.calendar;

import java.util.hashmap;

import java.util.list;

import java.util.map;

import net.sf.json.jsonobject;

import org.apache.log4j.logger;

/**此处略去一部分代码**/

@controller

@requestmapping(value = “/import”, method = { requestmethod.get,requestmethod.post })

public class importcontroller extends basecontroller{

         /** 用于打印日志 */

         private static final logger logger = logger

                            .getlogger(specialcontroller.class);

/**

          * 图片上传

          * @param param

          * @param imagefile

          * @return

          */

         @requestmapping(value = “/uploadpicture”, produces = “text/json”)

         @responsebody

         public string uploadpicture(@requestparam(“file”) multipartfile imagefile) {

                   map<string, object> result = new hashmap<string, object>();

                   if (!imagefile.isempty()) {

                            try {

                                     calendar calendar = calendar.getinstance();//获取当前时间

                                     //时间路径,解压文件,以年月日创建文件夹

                                     string datapath =”/”+calendar.get(calendar.year)+”/”

                                                                 + (calendar.get(calendar.month)+1)+”/” + calendar.get(calendar.date)+”/”;

                                     // 原文件名

                                     string srcname = imagefile.getoriginalfilename();

                                     //获取上传文件后缀

                                     string suffix = srcname.substring(srcname.lastindexof(“.”) + 1,

                                                        srcname.length()).tolowercase();

                                     //随机生成32位id,用于解压文件目录

                                     string uuid = uuidgenerator.generate();

                                     //新的文件名,随机的uuid;

                                     string picname = uuid +”.”+suffix;

                                     //上传图片生成路径

                                     string imgpath =extendedserverconfig.getinstance()

                                                                 .getstringproperty(“thumbnail_path”)+ extendedserverconfig.getinstance()

                                                                 .getstringproperty(“background_img_path”)+datapath;

                                     //生成图片预览路径

                                     string picturepath =extendedserverconfig.getinstance()

                                                        .getstringproperty(“background_img_path”)+datapath+picname;

                                     //文件夹不存在,则创建

                                      file destfile = new file(imgpath);

                                        if(!destfile.exists()){

                                                  destfile.mkdirs();

                                        }

                                     // 写文件

                                     inputstream fi = imagefile.getinputstream();

                                     //上传文件写入到配置文件夹下

                                     fileutils.writefile(fi, imgpath+picname);

                                     file file = new file(imgpath+picname);

                                     if(file.exists()){

                                         result.put(“imgpath”, picturepath);//返回的图片预览路径

                                         result.put(“ilename”, srcname);

                                     }

                            } catch (exception e) {

                                     e.printstacktrace();

                            }

                   }

                   return jsonobject.fromobject(result).tostring();

         }

}

4、编写uploadify的js上传方法:

 * 背景图片上传

 * @param uploadid 背景设置中"选择"按钮的id

 * @param imgdivid 背景设置中"图片"小预览图所在div的id

 * @param imgsrcid 背景设置中"img标签的id,给src赋值用到

 * @param bgimgpath 隐藏的文本框值,存储的是图片路径,取消是用到

 * @param childpathofselectedelement 表示被选择了的

 * @param posflag 表示对应的是针对谁进行标题设置

 *                "0":表示标题

 *                "1": 表示列表

 */

function uploadbackgroundimg(uploadid,imgdivid,imgsrcid,bgimgpath,childpathofselectedelement,posflag){

   $("#"+uploadid).uploadify({

        //是否自动上传

        'auto':true,

        'height':37,

        'swf': scriptspath+"/uploadify/uploadify.swf",

        //文件选择后的容器id

        'queueid':'uploaditemlist',

        'fileobjname':'file',

        //上传处理程序

        'uploader': basepath+'/import/uploadpicture.action;jsessionid=' + jsessionid,

        //允许上传的文件后缀

        'filetypeexts':'*.jpg;*.gif;*.png;',

        //上传文件的大小限制

        'filesizelimit':'300mb',

        //上传数量

        'queuesizelimit' : 1,

        'queueid': 'filequeue',

        //上传到服务器,服务器返回相应信息到data里

        'onuploadsuccess':function(file, data,response){

           var o = $.parsejson(data);

           var imgpath = o.imgpath;

           if(imgpath=="" || imgpath ==null){

              alert("图片上传不成功");

           }else{

              $("#"+imgdivid).show();

              var path = vpath +imgpath;

              $("#"+imgsrcid).attr("src",path);

              $("#"+bgimgpath).val(imgpath);

              var id = selectedelementinfo.get("id"); //获得id的属性值

              $.tplcomponentlistsetting.removecss(id,childpathofselectedelement,"background-image");//移除原来的背景图片

              var stylecss = $("#generatedcss").text();

              var styletext = "#" + id + childpathofselectedelement +" {background-image: url('"+path+"') !important;}";

            //替换或者在最后拼接

            stylecss += "\r\n" + styletext;

            $("#generatedcss").text(stylecss);

            //表示的是标题

            if("0" == posflag){

                //设置相关的参数信息

                $("." + id + "_titlebackgroundabsoluteimg").val(path);

                $("." + id + "_titlebackgroundrelativeimg").val(imgpath);

            }

            //表示的是列表

            else if("1" == posflag) {

                console.log("此处暂时略掉");

           }

        }

    });

注意上面的'uploader': basepath+'/import/uploadpicture.action;jsessionid=' + jsessionid,