本次实现所有格式文件下载,包括浏览器可以直接打开的jpg也要下载,而不是直接打开
实现方式:
前端:
1.获取需要下载的url,
a.url标签包括需要访问的控制层路径,比如/QueryPage/download,其中QueryPage为QueryPageController控制器,download为该控制器下的一个下载方法
b.接下来就是需要携带的参数,比如需要下载的文件路径、文件名称等等,如下
/Upload/2021-08-14/20210814151233497.jpg
c.拼接链接url
其中urlArr为后端传回来的文件地址和名称,因为文件地址后面携带的名称是时间戳,所以这里需要再传文件名,比如以上那个时间戳的实际文件名称为,路人甲.jpg
let url = "/QueryPage/download?filePath=" + urlArr[1] + "&fileName=" + urlArr[0];
url拼接完后,接下来是一个关键步骤,这里采用a标签,不过a标签不是现成写好的,是临时生成的,然后隐藏起来,如下图js方法
function download(getur) {
var str = document.createElement("a");//创建a标签
str.href = getur;
document.body.appendChild(str);
str.click();
str.style.display = "none";//隐藏标签
}
传入的getur就是上面我刚才拼接的url。
在前端的完整写法为:
let downloadURL;
$.ajax({
url: "@Href("~/QueryPage/getURL")",
async: false,
type: "GET",
data: {
'id': downloadId
},
dataType: "text",
success: function (data) {
console.log('ajax返回值:',data);
downloadURL = data;
}
});
//以上方法只是说明获取url的过程,这里读者可以改成自己想要的任何方法
console.log('ajax返回的downloadURL的值:', downloadURL);
let urlArr = downloadURL.split('&');
let url = "/QueryPage/download?filePath=" + urlArr[1] + "&fileName=" + urlArr[0];
//执行下载
download(url);
后端实现
所有引用,可根据实际情况增删
using Model;
using Newtonsoft.Json;
using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using System.IO;
控制层实现
[HttpGet]
public ActionResult download(string filePath,string fileName)
{
filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);
//string fileName = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];//以字符流的形式下载文件
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentType = "application/octet-stream";//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
return new EmptyResult();
}