在csv文件下载后使用jQuery / Javascript打开另存为对话框

时间:2016-10-03 08:35:29

标签: javascript jquery asp.net-mvc c#-4.0

我试图在用户点击按钮后打开另存为对话框,但需要将文件发送到下载文件夹。我想提示用户保存文件的位置。

这是我到目前为止的Javascript函数:

function exportOBCSerialsToCSV(e) {
    var dataSource = $("#vehicleGrid").data("kendoGrid").dataSource;

    var filteredDataSource = new kendo.data.DataSource({
        data: dataSource.data(),
        filter: dataSource.filter()
    });

    filteredDataSource.read();

    var data = filteredDataSource.view();
    var result = '';

    for (var dataRow = 0; dataRow < data.length; dataRow++) {
        result += data[dataRow].OBCSerial + ',';
        if (dataRow == data.length - 1) {
            result += data[dataRow].OBCSerial;
        }
    }
    if (window.navigator.msSaveBlob) {
        window.navigator.msSaveBlob(new Blob([result]), 'OBC Serials.csv');
    }
    else if (window.URL != null) {
        var a = document.createElement('a');
        result = encodeURIComponent(result);
        a.href = 'data:application/csv;charset=UTF-8,' + result;
        a.download = 'OBC Serials.csv';
        a.click();
    }
    else {
        window.open(result);
    }
    e.preventDefault();
}

1 个答案:

答案 0 :(得分:0)

以下可能性:

  1. 在服务器上设置文件的标题,如下所示:
  2. Below possibilities :
    
    1. Set the header of the file on the server, like so:
    
    <FilesMatch "\.(?i:pdf)$">
       ForceType application/octet-stream
       Header set Content-Disposition attachment
    </FilesMatch>
    
    The download attribute does not allow you to change the filename or filetype any more as it is an obvious security risk.
    
    What you are trying to do it replicate the right-click - save-as dialogue but I'm afraid that is not possible at this time.
    
    2. When user's browser is set to automatically download all files in default location which is why not only this file but all other files from user's browser were downloaded directly without the save prompt dialogue. Changing the settings in browser to 'always ask the download location' can work.

    download属性不允许您更改文件名或文件类型,因为它存在明显的安全风险。 你试图做的是复制右键单击 - 另存为对话,但我担心此时不可能。

    1. 当用户的浏览器设置为自动下载默认位置的所有文件时,这就是为什么不是这个文件而是用户浏览器中的所有其他文件都直接下载而没有保存提示对话框。将浏览器中的设置更改为“始终询问下载位置”可以正常工作。