尝试创建一个使用 web api 下载服务器中现有文件的函数。该 api 似乎正在返回数据,但是当我尝试使用 javascript 下载文件并使用 Ms Word 打开它时,我总是收到错误消息。
下面是使用web api获取文件的方法
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');
}
当我打开文件时出现此错误