基於jQuery Ajax實現無重新整理檔案上傳

來源:互聯網
上載者:User

標籤:adf   tip   ipa   功能   頁面   實現   span   jsp頁面   form   

最近因項目需求更改,需要實現選擇檔案後即時上傳至伺服器,然後提交後,載入xls表格內容到jqgrid表格中,檔案上傳功能實現樣本:

前端jsp頁面:

<form id="uploadForm" enctype="multipart/form-data">  <!-- 聲明檔案上傳 -->  <input id="file_upload" type="file" name="pic" onchange="fileChange(‘${base }‘)"/>  <!-- 定義change事件,選擇檔案後觸發 -->  <input type="hidden" name="modelName" value="famoxuke" />     <!-- 項目需求欄位,非必須 -->  <br/><span style="color: red" id="fileTypeError"></span>    <!-- 檔案類型錯誤回顯,此處通過前後端兩次驗證檔案類型 --></form>

js代碼:

function fileChange(base){    $("#fileTypeError").html(‘‘);    var fileName = $(‘#file_upload‘).val();                  //獲得檔案名稱    var fileType = fileName.substr(fileName.length-4,fileName.length);  //截取檔案類型,如(.xls)    if(fileType==‘.xls‘ || fileType==‘.doc‘ || fileType==‘.pdf‘){     //驗證檔案類型,此處驗證也可使用正則        $.ajax({            url: base+‘/actionsupport/upload/uploadFile‘,          //上傳地址            type: ‘POST‘,            cache: false,              data: new FormData($(‘#uploadForm‘)[0]),             //表單資料            processData: false,            contentType: false,            success:function(data){                if(data==‘fileTypeError‘){                    $("#fileTypeError").html(‘*上傳檔案類型錯誤,支援類型: .xsl .doc .pdf‘);  //根據後端傳回值,回顯錯誤資訊                }                $("input[name=‘enclosureCode‘]").attr(‘value‘,data);            }        });    }else{        $("#fileTypeError").html(‘*上傳檔案類型錯誤,支援類型: .xls .doc .pdf‘);    }}

後端action代碼:

public String uploadFile(@RequestParam("pic")CommonsMultipartFile pic,HttpServletRequest req,HttpServletResponse response,String modelName) throws IOException{
//檔案儲存代碼及業務處理,後台mvc使用springMVC,此時只展示方法參數類型,飄紅標記,具體檔案儲存代碼簡單,不作贅述.
return xxxxx; }

後記:由於此功能實現input選擇後即時上傳,所以對於檔案類型的限定和判斷建議前後端都要做,防止使用者錯誤提交不正確的檔案,白白浪費伺服器硬碟空間.

基於jQuery Ajax實現無重新整理檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.