直接上代码:
let url = ApiUrl +"/Query/download?filePath=" + data.url + "&fileName=" + data.title; //执行下载 download(url);
function download(getur) { //通过http.status状态码返回资源存在情况 let http = new XMLHttpRequest(); http.open('GET', getur, false); http.send(); console.log('http.status:',http.status); let str = document.createElement("a");//创建a标签 str.href = getur; document.body.appendChild(str); str.style.display = "none";//隐藏标签 str.click(); }
C#服务端代码
private HttpResponseMessage downloadCom(string filePath, string fileName)
{
//先要判断下载的文件是否还存在
if (File.Exists(filePath))
{
var stream = new FileStream(filePath, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);//这里返回200
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
return response;
}
else
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);//这里返回404不存在
return response;
}
}