ExtJS 4.2.3附件列表点击时替换直接下载为打开/保存对话框
解决ExtJS附件点击弹出打开/保存对话框的问题
嘿,我来帮你搞定这个需求!你现在的代码是用window.location直接跳转到下载链接,这会让浏览器根据文件类型直接处理(比如直接打开PDF、图片),而不是弹出选择对话框。咱们可以通过创建隐藏的<a>标签来触发下载,轻松唤起浏览器的默认“打开/保存”对话框。
修改后的完整代码
Ext.onReady(function () { var trGuid = Ext.Object.fromQueryString(location.search).trGUID; Ext.define("File_model", { extend: "Ext.data.Model", fields: [ { name: 'document_GUID', type: 'string' }, { name: 'attachment_fileName', type: 'string' }, ] }); // end Model Ext.create('Ext.data.Store', { storeId: 'FileStore', model: "File_model", proxy: { type: 'jsonp', url: 'http://test/AttachmenttoHTML/List', extraParams: { trGUID: trGuid }, reader: { type: 'json', root: 'data' } }, autoLoad: true }); // end Store FileGrid = new Ext.grid.Panel({ renderTo: "EXT-CONTENT", width: 750, height: 500, listeners: { cellclick: function (table, td, cellIndex, record, tr, rowIndex, e) { var url = 'http://test/Attachment/Get?document_GUID=' + record.get("document_GUID"); var fileName = record.get("attachment_fileName"); // 创建隐藏的a标签来触发下载 var downloadLink = document.createElement('a'); downloadLink.href = url; // 指定文件名,让对话框显示正确的文件名 downloadLink.download = fileName; downloadLink.style.display = 'none'; document.body.appendChild(downloadLink); // 模拟点击触发下载 downloadLink.click(); // 用完后移除标签,避免DOM冗余 document.body.removeChild(downloadLink); } }, columns: { defaults: { filter: true }, items: [ { text: 'Name', dataIndex: 'attachment_fileName', width: 748, cellWrap: true } ] }, store: Ext.data.StoreManager.lookup('FileStore') }); // end TaskGrid }); // end onReady
关键修改说明
- 替换了原来的
window.location = url逻辑,改用创建<a>标签的方式触发下载,这是让浏览器弹出选择对话框的核心操作 - 设置
download属性,绑定从接口获取的原始文件名,让对话框能显示正确的文件名称 - 临时创建的标签在触发下载后立即移除,不会留下无用的DOM元素
额外优化建议
如果想让效果更稳定,建议后端在返回文件时设置正确的Content-Disposition响应头,示例(以C#为例):
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + 文件名 + "\"");
这个响应头会明确告诉浏览器“这是一个需要下载的附件”,进一步确保弹出“打开/保存”对话框,避免浏览器直接打开可预览的文件类型。
内容的提问来源于stack exchange,提问作者Dmitry
相关产品推荐
相关产品推荐

