1. 程式人生 > >struct2實現多檔案上傳利用ajaxfileupload.js外掛

struct2實現多檔案上傳利用ajaxfileupload.js外掛

1.前端利用ajaxfileupload.js外掛實現,原生外掛預設不支援多個檔案上傳,需要修改外掛原始碼來支援
外掛js程式碼如下
修改的原始碼為將createUploadForm函式內

  //單個檔案上傳
  var oldElement = jQuery('#' + fileElementId); //得到頁面中的<input type='file' />物件
  var newElement = jQuery(oldElement).clone(); //克隆頁面中的<input type='file' />物件
  jQuery(oldElement).attr('id'
, fileId); //修改原物件的id jQuery(oldElement).before(newElement); //在原物件前插入克隆物件 jQuery(oldElement).appendTo(form); //把原物件插入到動態form的結尾處

替換為如下:

//修改原始碼:支援ajax批量上傳檔案
        for(var i in fileElementId){  
            var oldElement = jQuery('#' + fileElementId[i]);  
            var newElement = jQuery(oldElement).clone();  
            jQuery(oldElement).attr('id'
, fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); }
以下為修改之後的ajaxfileupload.js的原始碼
jQuery.extend({


    createUploadIframe: function (id, uri) {//id為當前系統時間字串,uri是外部傳入的json物件的一個引數
        //create frame
        var frameId = 'jUploadFrame'
+ id; //給iframe新增一個獨一無二的id var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //建立iframe元素 if (window.ActiveXObject) {//判斷瀏覽器是否支援ActiveX控制元件 if (typeof uri == 'boolean') { iframeHtml += ' src="' + 'javascript:false' + '"'; } else if (typeof uri == 'string') { iframeHtml += ' src="' + uri + '"'; } } iframeHtml += ' />'; jQuery(iframeHtml).appendTo(document.body); //將動態iframe追加到body中 return jQuery('#' + frameId).get(0); //返回iframe物件 }, createUploadForm: function (id, fileElementId, data) {//id為當前系統時間字串,fileElementId為頁面<input type='file' />的id,data的值需要根據傳入json的鍵來決定 //create form var formId = 'jUploadForm' + id; //給form新增一個獨一無二的id var fileId = 'jUploadFile' + id; //給<input type='file' />新增一個獨一無二的id var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //建立form元素 if (data) {//通常為false for (var i in data) { jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根據data的內容,建立隱藏域,這部分我還不知道是什麼時候用到。估計是傳入json的時候,如果預設傳一些引數的話要用到。 } } //修改原始碼:支援ajax批量上傳檔案 for(var i in fileElementId){ var oldElement = jQuery('#' + fileElementId[i]); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); } //單個檔案上傳 // var oldElement = jQuery('#' + fileElementId); //得到頁面中的<input type='file' />物件 // var newElement = jQuery(oldElement).clone(); //克隆頁面中的<input type='file' />物件 // jQuery(oldElement).attr('id', fileId); //修改原物件的id // jQuery(oldElement).before(newElement); //在原物件前插入克隆物件 // jQuery(oldElement).appendTo(form); //把原物件插入到動態form的結尾處 //set attributes jQuery(form).css('position', 'absolute'); //給動態form新增樣式,使其浮動起來, jQuery(form).css('top', '-1200px'); jQuery(form).css('left', '-1200px'); jQuery(form).appendTo('body'); //把動態form插入到body中 return form; }, ajaxFileUpload: function (s) {//這裡s是個json物件,傳入一些ajax的引數 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); //此時的s物件是由jQuery.ajaxSettings和原s物件擴充套件後的物件 var id = new Date().getTime(); //取當前系統時間,目的是得到一個獨一無二的數字 var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //建立動態form var io = jQuery.createUploadIframe(id, s.secureuri); //建立動態iframe var frameId = 'jUploadFrame' + id; //動態iframe的id var formId = 'jUploadForm' + id; //動態form的id // Watch for a new set of requests if (s.global && !jQuery.active++) {//當jQuery開始一個ajax請求時發生 jQuery.event.trigger("ajaxStart"); //觸發ajaxStart方法 } var requestDone = false; //請求完成標誌 // Create the request object var xml = {}; if (s.global) jQuery.event.trigger("ajaxSend", [xml, s]); //觸發ajaxSend方法 // Wait for a response to come back var uploadCallback = function (isTimeout) {//回撥函式 var io = document.getElementById(frameId); //得到iframe物件 try { if (io.contentWindow) {//動態iframe所在視窗物件是否存在 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) {//動態iframe的文件物件是否存在 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") {//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); //根據傳送的type型別,返回json物件,此時返回的data就是後臺操作後的返回結果 // 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]); } 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 if (s.complete) s.complete(xml, status); jQuery(io).unbind();//移除iframe的事件處理程式 setTimeout(function () {//設定超時時間 try { jQuery(io).remove();//移除動態iframe jQuery(form).remove();//移除動態form } 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);//傳入的ajax頁面導向url jQuery(form).attr('method', 'POST');//設定提交表單方式 jQuery(form).attr('target', frameId);//返回的目標iframe,就是建立的動態iframe if (form.encoding) {//選擇編碼方式 jQuery(form).attr('encoding', 'multipart/form-data'); } else { jQuery(form).attr('enctype', 'multipart/form-data'); } jQuery(form).submit();//提交form表單 } catch (e) { jQuery.handleError(s, xml, null, e); } jQuery('#' + frameId).load(uploadCallback); //ajax 請求從伺服器載入資料,同時傳入回撥函式 return { abort: function () { } }; }, 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] ); } }, 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" ) //data = data.replace("<pre>","").replace("</pre>",""); data = jQuery.parseJSON(jQuery(data).text()); //data = eval("("+data.replace("<pre>","").replace("</pre>","")+")"); // evaluate scripts within html if (type == "html") jQuery("<div>").html(data).evalScripts(); return data; } })

2.檔案上傳jsp檔案,可支援多個檔案上傳,在這裡對上傳的檔案型別進行過濾,只支援圖片型別的檔案
程式碼為:

<%@ page language="java" pageEncoding="utf-8" %>
<%@include file="/WEB-INF/pages/common/taglibs.jsp"%>
<html>
<head>
<title>上傳人臉照片</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8"  name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="${path}/js/ajaxfileupload.js" ></script>
<style type="text/css">
    input {
        border:1px solid;
        outline:none;
        line-height:normal;
        *overflow:visible
    }

    .inpo{
    margin-top: 20px;
    }


.divBig{
    height: 40px;
    text-align: center;
    margin-top:5%;
    margin-bottom: 5%;
}

    </style>

    <script type="text/javascript">

    function checkFaceInfo(){
        var userName = $("#userName").val();
        if(null !=userName && userName!=''){
            var fileNames = new Array();//存放檔案字尾名
            var ids = new Array();//存放檔案id
            $("#ta").find("input[name='file']").each(function (index){
                 var id = $(this).attr("id");
                 var excelName = $(this).val();
                 fileNames.push(excelName);
                 ids.push(id);
            })

            var flag = false;
            for(var i=0;i<fileNames.length;i++){
                //檔案格式校驗
                var fileTArr=fileNames[i].split(".");
                var filetype=fileTArr[fileTArr.length-1];
                if(filetype!=null && filetype!=""){
                    if(filetype == "jpg" || filetype == "png" || filetype == "jpeg" || filetype == "gif"){
                        flag=true;
                    }else{
                        $.messager.alert('提示',"請上傳正確的圖片檔案,僅支援字尾為'jpg'、'png'、'jpeg'、'gif'的圖片檔案!",'info');
                        break;
                    }
                }else{
                    $.messager.alert('提示',"請上傳(字尾為'jpg'、'png'、'jpeg'、'gif')圖片檔案!",'info');
                    break;
                }
            }

            if(flag){
                $.ajaxFileUpload({
                    url: $.contextPath + "/faceInfoOp_batchUploadFile", 
                    type: 'post',
                    secureuri: false, 
                    data:{
                        'userName':userName
                    },
                    fileElementId: ids,
                    dataType: 'json', 
                    success: function(rel, status){  
                        if(rel.result=='success'){
                            $uidialog.dialog('close');
                             getFaceList('');
                              $.messager.show({
                                  title:'提示',
                                  msg:'上傳人臉照片成功!',
                                   timeout:3000,
                                   showType:'slide'
                               });
                        }else if(rel.result=='noUser'){
                            $.messager.alert('提示',"該使用者未找到!",'error');
                        }else if(rel.result=='noFile'){
                            $.messager.alert('提示',"上傳檔案格式有誤!",'error');
                        }else{
                            $.messager.alert('提示',"上傳過程發生錯誤!",'error');
                        }
                    },
                    error: function(data, status, e){
                         $.messager.alert('提示', '與伺服器通訊失敗,請稍後再試!', 'error');
                    }
                 });

            }
        }else{
            $.messager.alert('提示',"請輸入使用者名稱 !",'info');
        }
    }

    var add_count=2;
    function addface(){
        var table = $("#ta");
        var tr=$("<tr id='tr"+add_count+"'></tr>");
        var td1=$("<td width='30%' style='text-align:left;' bgcolor='#fafcfd'><span style='color: red;' >*</span>人臉照片:</td> ");
        var td2=$("<td width='50%'><input type='file' name='file' id='file"+add_count+"' value='' style='width:160px;height:22px;'/></td>");
        var td3=$("<td width='20%'><button id='btn_upload' onclick='delFace("+add_count+")' class='btn btn-warning' type='button' style='margin:auto 0;'>刪除</button></td>");
        tr.append(td1);
        tr.append(td2);
        tr.append(td3);
        table.append(tr);
        add_count++;
        add_time++;
    }


    function delFace(id){
        $("#tr"+id+"").remove();
         add_count--;
    }
</script>

</head>
<body>
    <div style="margin-top: 10px;">
            <table id="ta" width="95%" class="list" border="0" cellpadding="0" cellspacing="0" align="center">
                <tr>
                    <td width="30%" style="text-align:left;" bgcolor="#fafcfd"><span style="color: red;" >*</span>使用者名稱:</td>
                    <td width="50%"><input type="text" name="userName" id="userName" value="" style="width:160px;height:22px;" /></td>
                    <td width="20%"></td>
                 </tr>

                <tr>
                    <td width="30%" style="text-align:left;" bgcolor="#fafcfd"><span style="color: red;" >*</span>人臉照片:</td>
                    <td width="50%" ><input type="file" name="file"  id="file1" value="" style="width:160px;height:22px;" /></td>
                    <td width="20%" ><button id="btn_upload"  onclick="addface();" class="btn btn-warning" type="button" style="margin:auto 0;">新增</button></td>
                 </tr>
            </table>
    </div>

        <div class="divBig">
            <button id="btn_upload"  onclick="checkFaceInfo();" class="btn btn-warning" type="button" style="margin:auto 0;">確認</button>
        </div>

</body>
</html>

3.後臺部分利用struct2框架實現
後臺Action部分

private File[] file;//上傳的檔案
private String[] fileFileName;//上傳的檔名
private String[] fileFileContentType;//上傳的檔案型別
private String userName;//使用者名稱

public File[] getFile() {
        return file;
    }
    public void setFile(File[] file) {
        this.file = file;
    }
    public String[] getFileFileName() {
        return fileFileName;
    }
    public void setFileFileName(String[] fileFileName) {
        this.fileFileName = fileFileName;
    }
    public String[] getFileFileContentType() {
        return fileFileContentType;
    }
    public void setFileFileContentType(String[] fileFileContentType) {
        this.fileFileContentType = fileFileContentType;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
/**
      * 批量上傳人臉照片
      *@author LH
      *@data 2018年4月26日
      * @return
      */
    public String batchUploadFile(){
        log.loger.info("batchUploadFile start!");
        jsonMap = new JSONObject();
        jsonMap = faceInfoManager.batchUploadFile(userName,file,fileFileName);
        log.loger.info("json="+jsonMap);
        return SUCCESS;
    }
//呼叫service層
@Override
    public JSONObject batchUploadFile(String userName , File[] files, String[] fileFileNames) {
        JSONObject jsonObject = new JSONObject();
        try {
            User userinfo = userManager.findByAccount(userName);
            if(null !=userinfo){
                String trainPath = Util.getValueFromConf(BaseConstant.TRAING_DIR,BaseConstant.FACE_CFG);
                if(null !=files && files.length>0){
                    int count = files.length;
                    int s=0;
                    for(int i=0;i<files.length;i++){
                        if(null !=files[i] && files[i].isFile()){
                            int maxNum = faceInfoDao.getMaxNum();
                            int num=BaseConstant.FACE_NUM;
                            if(maxNum!=0){
                                num=maxNum+1;
                            }
                            //人臉圖片命名:編號+"_"+使用者名稱+"_"+8位隨機數
                            StringBuffer imageName = new StringBuffer();
                            String randomNum = RandomUtil.randomString(8);
                            imageName.append(num).append("_").append(userinfo.getUsername()).append("_").append(randomNum);
                            String serverFileName = imageName.toString() + FileUtil.getExtention((fileFileNames[i]));
                            //人臉圖片儲存路徑
                            String imagePath=trainPath + serverFileName;
//                          log.loger.info("imagePath="+imagePath);
                            File uploadFile = new File(imagePath);
                            //轉存到伺服器
                            boolean result = FileUtil.storeFile(files[i], uploadFile);
                            if(result){
                                log.loger.info("upload face image to server success!");
                                //儲存一條人臉上傳記錄
                                FaceInfo faceInfo = new FaceInfo();
                                faceInfo.setUsername(userName);//儲存使用者名稱
                                faceInfo.setFaceNumber(num);//儲存人臉圖片編號
                                faceInfo.setFacePath(imagePath);//儲存人臉圖片路徑
                                faceInfo.setCreateTime(new Date());//建立時間
                                faceInfo.setLastUpdateTime(new Date());//修改時間
                                boolean rel = faceInfoDao.saveFaceInfo(faceInfo);
                                if(rel){
                                    s++;
                                }
                            }else{
                                log.loger.info("uplod face image to server error,image name is="+fileFileNames[i]);
                            }
                        }else{
                            log.loger.info("file is not find");
                        }
                    }

                    if(count==s){
                        jsonObject.put("result", "success");
                    }else{
                        jsonObject.put("result", "fail");
                    }
                }else{
                    jsonObject.put("result", "noFile");
                }
            }else{
                jsonObject.put("result", "noUser");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.loger.error("uploadFaceImage happen exception!"+e);
            jsonObject.put("result", "exception");
        }
        return jsonObject;
    }

需要注意的是要測試中發現多個檔案上傳時會報臨時檔案找不到進過查詢資源發現需要在struts.xml配置檔案中新增一項配置項,用於暫時存放上傳的檔案
在struct2.xml新增的配置如下:

 <constant name="struts.multipart.saveDir" value="/tmp"/>

相關推薦

struct2實現檔案利用ajaxfileupload.js外掛

1.前端利用ajaxfileupload.js外掛實現,原生外掛預設不支援多個檔案上傳,需要修改外掛原始碼來支援 外掛js程式碼如下 修改的原始碼為將createUploadForm函式內 //單個檔案上傳 var oldElement = jQu

webuploader+springmvc實現檔案(html+js+css原創,後臺程式碼借鑑)

———————-css—————————- /*新增圖片按鈕*/ .add_resume_item { cursor: pointer; } /*遮罩層*/ .zpzs_gray { position: fixed; left: 0; to

ajax 利用formdata物件 實現檔案

$(function(){ $("#btn").click(function(){ var formData = new FormData(); for(var i=0; i<$('#file')[0].files.l

Jfinal框架下結合ajaxFileupload實現檔案

距離寫程式碼時間有點長了,沒有及時總結,現在忘得差不多了。不過大概思路還在,也是有點參考價值的! 思路: 由於jfinal框架自身的問題,在實現多檔案上傳時很難獲取所有檔案的名字,只能獲取到一個input標籤裡面的名字而已,重寫框架是最佳的方法,但是對於初學者而言十分艱

ajaxFileUpload+struts2實現檔案(動態新增檔案框)

但只是固定的檔案個數,如果需求不確定是多少檔案 則我們就需要動態的新增檔案上傳框,以實現靈活性。基於上篇基本框架是不變的,主要修改以下幾個方面1、jQuery實現動態新增刪除檔案上傳框2、獲取檔案上傳框

ajaxFileUpload+struts2實現檔案

以前有介紹過ajaxFileUpload實現檔案上傳,但那是單檔案的,這次介紹多檔案上傳。單檔案和多檔案的實現區別主要修改兩點,一是外掛ajaxfileupload.js裡接收file檔案ID的方式二是後臺action是陣列形式接收2、引入jquery-1.8.0.min.j

TP5實現檔案及展示

view層上傳: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body&

webuploader實現檔案

問題:  1: 上傳失敗,不知道怎麼在服務端寫返回值?  2: 做個多檔案上傳怎麼辦?  1:上傳失敗,不知道怎麼在服務端寫返回值? (1):首先在初始化Web Uploader  的方法寫上 server: 'http://localho

在SSM框架中使用AJAX實現檔案

今天來學習一下在SSM框架中使用ajax實現檔案的上傳。 1.首先我們需要一個搭建好的SSM框架專案,這個在這篇文章裡不是重點,自行先搭建好需要的專案。 這裡我是用的jsp頁面來和後臺介面關聯,在jsp檔案中我們需要一個form表單,請求方法為POST,enctype="mu

Java Web FormData格式資料流實現檔案

1.html <``input type="file" multiple="multiple" accept="image/gif, image/jpeg, image/png, image/jpg, image/bmp" /> 2.JS $(document).on("ch

java實現檔案01

1、html程式碼 <html> <head> <link rel="stylesheet" type="text/css" href="table.css" /> <link rel="stylesheet" type="text/css"

Spring MVC實現檔案

1、修改POJO和DAO實現類  public class User{ //......其他屬性省略 private String idPicPath;//證件照路徑 private String workPicPath;//工作證照片路徑

java實現檔案至本地伺服器

博主最近在做一個內網專案,內部可以訪問外部資料,但是外部訪問不了內部資料,這也就造成了可能檔案無法上傳,所以博主另闢蹊徑,在本地伺服器上建立一個資料夾專門用來儲存上傳資料。 環境:jdk,tomcat 一、前臺上傳檔案(ajax上傳) <input type=

ASP.NET MVC實現檔案

要實現ASP.NET MVC中的多檔案上傳,其實最關鍵的一步是要在input上定義multiple屬性,使之可以支援多檔案上傳。 其實有幾個比較重要的地方,form一定要申明enctype=“multipart/form-data”,其次是  <input type=

layui.js實現檔案前端html寫法總結

最近需要寫多檔案上傳功能,用到了layui.js控制元件,現進行總結,因為內容太多這裡只總結了html頁面的內容,java後臺配置對接另一篇文章《layui上傳多檔案後臺程式碼總結(java》,其實官網《layui.js檔案上傳示例》已經寫的很詳細了,我再囉嗦一下。 參考文章如下: layu

SWFUpload實現檔案DEMO

         引言:最近專案中需要用到多檔案上傳,在網上找了很多資料,最開始使用的是uploadify這個外掛,在使用的過程中各種問題,什麼Flash版本的問題,瀏覽器相容性的問題總之是一大堆,最後在眾多問題下,無奈只好放棄了。最後選擇了SWFUpload,在網上下載了

Struts2 實現檔案

前臺form 表單:設定method=post,enctype=multipart/form-data。 struts2在原有的上傳解析器繼承上做了進一步封裝,更進一步簡化了檔案上傳。 Action需要使用3個屬性來封裝該檔案域的資訊: (1)型別為Fil

js實現檔案

首先,將以下js程式碼放入頁面這裡我判斷的是隻能上傳xls格式的檔案,可以根據自己的需求修改js中的checkExcel方法 [javascript] view plaincopy </pre&

HttpClient使用MultipartEntityBuilder實現檔案

package com.jph.ufh.service; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import org.apache.http.Htt

實現檔案的例子

通過頁面實現多檔案上傳,並有進度條控制的例子,步驟參考如下(程式碼中涉及的幾個按鈕圖片參見附件) 1:頁面端實現多檔案上傳 ? <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF