Ajax 强制下载docx文件
尝试创建使用web api下载服务器中现有文件的函数。api似乎正在返回数据,但当我尝试使用javascript下载文件并用Ms Word打开时,总是会出现错误 下面是使用web api获取文件的方法Ajax 强制下载docx文件,ajax,docx,webapi,Ajax,Docx,Webapi,尝试创建使用web api下载服务器中现有文件的函数。api似乎正在返回数据,但当我尝试使用javascript下载文件并用Ms Word打开时,总是会出现错误 下面是使用web api获取文件的方法 private HttpResponseMessage ReturnFile(string filename) { //FileStream stream = new FileStream(HttpContext.Current.Server.MapPath("~") +
private HttpResponseMessage ReturnFile(string filename)
{
//FileStream stream = new FileStream(HttpContext.Current.Server.MapPath("~") + "\\Temp" + "\\" + filename, FileMode.Open, FileAccess.Read, FileShare.None);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
//Set the File Path.
string filePath = HttpContext.Current.Server.MapPath("~") + "\\Temp" + "\\" + filename;
//Check whether File exists.
if (!File.Exists(filePath))
{
//Throw 404 (Not Found) exception if File not found.
response.StatusCode = HttpStatusCode.NotFound;
response.ReasonPhrase = string.Format("File not found: {0} .", filename);
throw new HttpResponseException(response);
}
//Read the File into a Byte Array.
byte[] bytes = File.ReadAllBytes(filePath);
//Set the Response Content.
response.Content = new ByteArrayContent(bytes);
//Set the Response Content Length.
response.Content.Headers.ContentLength = bytes.LongLength;
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.Add("x-filename", filename); //We will use this below
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = filename;
response.Content.Headers.Add("Access-Control-Expose-Headers", "x-filename");
//Set the File Content Type.
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(filename));
return response;
}
下面是调用web api的post函数
function CallPostRestAPIDownload(url, data, callbacksuccess, callbackerror) {
$.ajax({
type: "POST",
async: false,
url: url,
contentType: "application/json",
dataType: "text",
data: JSON.stringify(data),
error: callbackerror,
success: callbacksuccess
});
}
下面是强制下载文件的函数
function DownloadDoc(data, status, xhr) {
console.log("data:" + JSON.stringify(data));
console.log("status:" + JSON.stringify(status));
console.log("xhr:" + JSON.stringify(xhr));
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
var downloadUrl = URL.createObjectURL(blob);
let filename = "";// headers['x-filename'];
console.log("getAllResponseHeaders:" + xhr.getAllResponseHeaders());
//console.log("getResponseHeader:" + xhr.getResponseHeader("x-filename"));
filename = xhr.getResponseHeader('x-filename');
console.log(filename);
let hiddenElement = document.createElement('a');
hiddenElement.href = downloadUrl;
hiddenElement.target = '_blank';
hiddenElement.download = filename;
hiddenElement.click();
//window.open(uri, 'newdownload.csv');
}
当我打开文件时,我发现了这个错误
这就是强制下载返回的内容
我设法找到了一种不用AJAX的方法
window.open(uri + "/" + FileId, "_blank");
只需将“下载”添加到href标记即可。请参阅W3Schools的此页。