下面是extjs列表中文件上傳與下載:
如圖:
一、上傳
上傳按鈕:
{ xtype: 'button', width: 60, margin: '0 20', text: ' 上 傳 ', handler: 'onUploadClick' }]
上傳按鈕事件(打開上傳窗口和傳參):
onUploadClick: function () { var me = this, view = me.getView(), vm = view.getViewModel(), store = me.getStore('gridstore'), filType = view.up('window').FIL_TYPE,//附件類型(1:項目附件,2:需求附件,3需求明細附件) fileId = view.up('window').FILE_RELATION_ID;//附件關系ID(項目表ID,需求表ID,需求明細表ID) var userOper = Ext.create('MainApp.view.comm.UploadOperation.Operation'); Ext.create('Ext.window.Window', { title: '上傳文件', resizable: false, constrain: true, modal: true, items: userOper, width: 400, height: 120, _up: this, FIL_TYPE: filType, FILE_RELATION_ID:fileId, listeners: { beforeclose: function () { store.reload(); } } }).show(); },
上傳窗口:

/* *********************************************** * author : zh * function: 上傳文件 * history: created by 2017/12/18 * ***********************************************/ Ext.define('MainApp.view.comm.UploadOperation.Operation', { extend: 'Ext.form.Panel', requires: [ 'MainApp.view.comm.UploadOperation.OperationController', 'MainApp.view.comm.UploadOperation.OperationModel', 'Fm.ux.form.FileUpload', 'Ext.window.MessageBox' ], alias: 'widget.Upload_Operation', controller: 'Upload_OperationController', viewModel: { type: 'Upload_Operation' }, modelValidation: true, tbar: [ { xtype: "form", frame: false, anchor: '100%', header: false, align: 'center', layout: 'hbox', defaults: { anchor: '100%', allowBlank: false, msgTarget: 'side', labelWidth: 60, }, resuiltTpl: new Ext.XTemplate( '文件{fileName}上傳成功!' //<br /> //'共{rowNum}條數據' ), items: [ { xtype: 'filefield', emptyText: '請選擇要上傳的文件', name: 'fileUpName', buttonText: '瀏覽…', width: 180, margin: '0 0 0 5' }, { xtype: 'button', text: '導入', margin: '0 0 0 5', handler: function () { var that = this.up('form'); var form = that.getForm(); if (form.isValid()) { var filType = this.up('window').FIL_TYPE;//附件類型(1:項目附件,2:需求附件,3需求明細附件) var fileRelationId = this.up('window').FILE_RELATION_ID;//附件關系ID(項目表ID,需求表ID,需求明細表ID) form.submit({ url: '/DataBase/UpLoadFile?filType=' + filType + '&fileRelationId=' + fileRelationId, waitMsg: '數據上傳中...', success: function (fp, o) { Ext.Msg.show({ title: '成功', msg: that.resuiltTpl.apply(o.result), minWidth: 200, modal: true, icon: Ext.Msg.INFO, buttons: Ext.Msg.OK, fn: function (btn) { var upw = that.up('window')._up; upw.onSearchClick(); } }); }, failure: function () { Ext.Msg.alert("失敗", Ext.JSON.decode(this.response.responseText).message); } }); } } }, { xtype: 'button', text: '清除', margin: '0 0 0 5', handler: function () { this.up('form').getForm().reset(); } }] } ], items: [ { xtype: 'panel', items: [ ], buttonAlign: 'center', buttons: [ { text: '關閉', width: 80, handler: 'onCancel' } ] }], });
上傳后台方法(重新使用guid命名,避免文件重復被替換,原名稱需要保存到數據庫):
/// <summary> /// 上傳文件 /// </summary> /// <returns></returns> [HttpPost] public ActionResult UpLoadFile(string filType,string fileRelationId) { try { WFile wfile = new WFile(); HttpPostedFileBase file = Request.Files[0]; if (file == null) { return Json(new { success = false, message = "沒有選擇文件!", errors = new { fileUpName = "上傳數據出錯!" } }); } //if (!file.FileName.Contains(".doc") && !file.FileName.Contains(".docx")) //{ // return Json(new { success = false, message = "文件格式不正確,只能上傳Word文件!", errors = new { fileUpName = "上傳數據出錯!" } }); //} string guId = Guid.NewGuid().ToString("N"); string extension = Path.GetExtension(file.FileName); var filePath = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(guId + extension)); file.SaveAs(filePath); //數據庫操作 wfile.FIL_TYPE = filType; wfile.FILE_RELATION_ID = fileRelationId; wfile.FIL_NAME = file.FileName; wfile.FIL_PATH = guId + extension; _wfile.Add(wfile); return Json(new { success = true, fileName = file.FileName, rowNum = 1 }); } catch (System.Exception ex) { return Json(new { success = false, message = ex.Message, errors = new { fileUpName = "上傳數據出錯!" } }); } }
二、下載
下載按鈕:
columns: [ { dataIndex: 'NUMROW', text: '序號', width: 40 }, { dataIndex: 'FIL_NAME', text: '附件名稱', flex: 1 }, { dataIndex: 'FIL_PATH', header: '文件路徑', align: 'center', flex: 1, hidden: true }, { dataIndex: 'USER_NAME', text: '創建人', flex: 1 }, { text: '上傳時間', dataIndex: 'CREATE_DATE', align: 'left', width: 125, flex: 1, renderer: Ext.util.Format.dateRenderer('Y-m-d') }, { text: '操作', xtype: 'actioncolumn', width: 80, flex: 1, items: [ { icon: '../images/redactBtn_down.PNG', handler: 'DownFile' }, ] } ],
下載按鈕事件:
DownFile: function (grid, rowIndex, colIndex, e, td, tr) { window.location.href = '/DataBase/DownFile?fileName=' + tr.get('FIL_NAME') + "&filePathName=" + tr.get('FIL_PATH'); }
下載后台方法(需要用原附件名稱替換guid名稱完成下載):
/// <summary> /// 下載附件 /// </summary> /// <param name="fileName">原文件名稱</param> /// <param name="filePathName">附件地址名稱</param> /// <returns></returns> public ActionResult DownFile(string fileName, string filePathName) { try { var filePath = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(filePathName)); FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; //通知瀏覽器下載文件而不是打開 System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); System.Web.HttpContext.Current.Response.BinaryWrite(bytes); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); return Json(new { success = true, fileName = fileName, rowNum = 1 }); } catch (System.Exception ex) { return Json(new { success = false, message = ex.Message, errors = new { fileUpName = "上傳數據出錯!" } }); } }
最后,常見問題補充,上傳文件大於4mb會發生錯誤:
解決辦法:配置config
<httpRuntime maxRequestLength="951200" targetFramework="4.5"/>