简体   繁体   中英

Force open a text file from javascript (file is on server)

I am generating several files upon clicking on a generate button. After successful generation of the file which is then stored on the server, the user is presented with the same file so he can download it.

I tried changing the extension to a known extension which cannot be opened directly by the browser, which is .doc. This worked as a popup shows stating to download the file.

However, I would like to change the extension to something which makes more sense, such as .cfg. The problem is that with a .cfg, or .txt the browser opens the file automatically (since it is a text file). How can I override this?

The following is the code:

c# server side:

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

extjs ajax call success code:

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.');                                                                                                                                                                                                                         
},

Basically, everything works fine with a .doc but I want to change it to .cfg

Any help?

Set response MIME type to "application/octet-stream" and optionally set a filename.

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM