从javascript强制打开文本文件(文件在服务器上)

时间:2012-07-12 13:54:38

标签: c# file extjs

点击生成按钮后,我生成了几个文件。成功生成然后存储在服务器上的文件后,会向用户显示相同的文件,以便下载。

我尝试将扩展名更改为已知的扩展名,该扩展名无法由浏览器直接打开,即.doc。这可以作为弹出窗口显示下载文件。

但是,我想将扩展名更改为更有意义的内容,例如.cfg。问题是,使用.cfg或.txt,浏览器会自动打开文件(因为它是文本文件)。我怎样才能覆盖这个?

以下是代码:

c#服务器端:

 string[] L_TextFile = P_Data.M_Content.Split('|');
 System.IO.File.WriteAllLines(@"c:\files\file.cfg", L_TextFile);
 response = "1";
 return response;

extjs ajax调用成功代码:

success: function(P_Response){
    var res = Ext.util.JSON.decode(P_Response.responseText);
    if(res == '1') window.location.href'/files/file.cfg';
    else ShowError('An error has occured while generating the text file.');                                                                                                                                                                                                                         
},

基本上,使用.doc一切正常,但我想将其更改为.cfg

任何帮助?

1 个答案:

答案 0 :(得分:3)

将响应MIME类型设置为"application/octet-stream",并可选择设置文件名。

示例:

response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
response.AddHeader("Content-Type", "application/octet-stream");