extjs列表中文件上传与下载(带有重命名操作)

Posted 小柒~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了extjs列表中文件上传与下载(带有重命名操作)相关的知识,希望对你有一定的参考价值。

下面是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"/>

 

 

 

以上是关于extjs列表中文件上传与下载(带有重命名操作)的主要内容,如果未能解决你的问题,请参考以下文章

apt无法重命名文件

WordPress 实现附件上传自动重命名但不改变附件标题

gitlab的基本操作--上传下载库的迁移/备份及回收/重命名

ASP.NET中的文件操作(文件信息,新建,移动,复制,重命名,上传,遍历)

在 Wordpress 中上传期间重命名文件

使用 AspNet 从 Azure Blob 存储下载和重命名文件