天天看點

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,