点击某些文字时我需要下载特定文件。我希望典型的“另存为...”对话框选择我要保存文件的位置,但它不会出现。请求和响应都可以。
请求/响应标头
GET / Survey / GetSurveyFile?survey = 1085& surveyFileType = 2 HTTP / 1.1
主持人:localhost:50518
连接:保持活力
User-Agent:Mozilla / 5.0(Windows NT 6.1; WOW64)AppleWebKit / 537.36(KHTML,与Gecko一样)Chrome / 44.0.2403.107 Safari / 537.36 OPR / 31.0.1889.99
接受: /
X-Requested-With:XMLHttpRequest
======================
HTTP / 1.1 200确定
缓存控制:私有
Content-Type:application / octet-stream
服务器:Microsoft-IIS / 8.0
X-AspNetMvc-Version:5.2
内容 - 处置:附件; filename =“1052__1183__1291__Variable Header Definition.txt”
X-AspNet-Version:4.0.30319
X-SourceFiles:=?UTF-8?B?UzpcVlNTb3VyY2VcUHJvamVrdGVcTU1JXGJmdWVudGVzXE1NSVxNaW5kc2hhcmUuTU1JXE1NSVxTdXJ2ZXlcR2V0U3VydmV5RmlsZQ ==?=
Persistent-Auth:true
X-Powered-By:ASP.NET
日期:星期一,2015年8月17日14:21:48 GMT
内容长度:333
我的代码:
的Javascript
function getfile(filetype) {
var SurveyId = $('#SurveyID').val();
var url = '/Survey/GetSurveyFile';
$.ajax({
type: 'GET',
url: url,
data: { survey: SurveyId, surveyFileType: filetype },
success: function (result) {
// ?
},
error: function (result) {
// handle errors
location.href = "/Home/"
}
});
}
控制器
public FileResult GetSurveyFile(string survey, string surveyFileType)
{
try
{
var tmpSurvey = EntityModelDataProvider.GetSurveyByID(int.Parse(survey));
var tmpSurveyFileTypes = EntityModelDataProvider.GetSurveyFileTypes();
var tmpSurveyFileType = tmpSurveyFileTypes.FirstOrDefault(_sft => _sft.SurveyFile_Type_Id == int.Parse(surveyFileType));
var tmpFile = EntityModelDataProvider.GetSurveyFilesBySurveyAndType(tmpSurvey.Survey_PK, tmpSurveyFileType.SurveyFile_Type_PK);
if (tmpFile != null)
{
byte[] fileBytes = tmpFile.SurveyFile;
string fileName = tmpFile.SurveyFile_Name;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
else
throw new Exception("File not found!");
}
catch (Exception ex)
{
throw ex;
}
}
任何想法我怎么能得到理想的行为?
答案 0 :(得分:1)
ORIGINAL(读后更新部分)
看这里download file using an ajax request
我在我的机器上尝试了下一个代码
function getfile() {
var p1 = Math.random().toString();
var p2 = Math.floor(Math.random() * 100);
window.location = '@Url.Action("Download")?' + 'p1=' + p1 + '&' + 'p2=' + p2;
}
$(function() {
$('h2').on('click', getfile);
});
public FileResult Download(string p1, int p2)
{
var bytes = System.IO.File.ReadAllBytes(Server.MapPath("~/123.txt"));
return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, string.Format("123_{0}_{1}.txt", p1, p2));
}
更新(第2版)
您不需要ajax请求。改变window.location就足够了:
<?xml version="1.0" encoding="UTF-8"?>
<Table1 Col1="xxx" Col2="xxx">
<Table2 Col1="xxx">
<Table3 Col1="xxx" Col2="xxx" Coln="xxx"/>
</Table2>
<Table2 Col1="xxx"/>
<Table2 Col1="xxx">
<Table3 Col1="xxx" Col2="xxx" Coln="xxx"/>
</Table2>
</Table1>