我必须将一个简单的txt文件下载到客户端PC,但在请求响应中,仅显示纯文本,而文件未下载。这是我的代码
df <- read.table(text =
"code Num mail identifier U_id
YY-12 12345 jjf@gmail.com ar145j U-111
YY-13 12345 jjf@gmail.com AR145J U-111
YY-14 48654 ert@gmail.com at188R U-112
YY-15 48654 Ert@gmail.com At189R U-113
YY-16 88994 fty@ymail.com fr789U U-114
YY-17 88994 fty@ymail.com fr789X U-115
YY-18 14500 foi@ymail.com xr747Y U-116
YY-19 14500 foi@ymail.com xY747C U-117", header = T)
我也尝试过返回没有结果的ActionResult类型。 这是我的ajax调用,
public virtual FileContentResult generateCKRM(string Code,string Name)
{
DataTable dt = new DataTable();
CHOO.TOSSRepository.TOSSRepository tr = new CHOO.TOSSRepository.TOSSRepository();
dt = tr.GetDetails(Code, Name);
return File(Encoding.UTF8.GetBytes(output), "text/plain", "CKRM_" + Code+ "_" + Name+ ".txt");
}
return null;
}
一切都很好,我可以在浏览器中看到响应,但没有文件正在下载。 Response Image
响应标题值如下
function GenerateFile() {
$('body').loader('show');
$.ajax({
url: '/Portal/generateCKRM',
data: {
'Code': $('#txtCode').val(), 'Name': $('#txtName').val()
},
type: 'GET',
contentType: "application/json; charset=utf-8",
datatype: 'json',
success: function (data) {
// window.location = 'file=' + data;
$('body').loader('hide');
},
error: function () { alert('Server Error! Please try again later.'); $('body').loader('hide'); }
});
}
更新: 我可以使用以下方式在Web表单应用程序中下载文件:
Cache-Control: private
Content-Disposition: attachment; filename=CKRM_Arew_8712.txt
Content-Encoding: gzip
Content-Length: 1387
Content-Type: text/plain
Date: Mon, 23 Jul 2018 08:50:13 GMT
Server: Microsoft-IIS/10.0
Vary: Accept-Encoding
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 5.2
X-Powered-By: ASP.NET
答案 0 :(得分:1)
为防止导航器显示文件,请使用application/octet-stream
:
return File(Encoding.UTF8.GetBytes(output), "application/octet-stream", "CKRM_" + Code+ "_" + Name+ ".txt");
并通过ajax下载文件:
$.ajax({
url: '/Portal/generateCKRM',
data: {
'Code': $('#txtCode').val(), 'Name': $('#txtName').val()
},
type: 'GET',
contentType: "application/json; charset=utf-8",
datatype: 'json',
success: function (data) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = 'file.txt';
a.click();
window.URL.revokeObjectURL(url);
$('body').loader('hide');
},
error: function () { alert('Server Error! Please try again later.'); $('body').loader('hide'); }
});