C# 下载文件
方法一:
[HttpGet]
[EnableCors("userLogin")]
public IActionResult DownloadFile(string url , string token)
{
var filePath = "D://xzc/" + _Configuration.GetSection("module").Value + "/Uploads/" + url;
string[] tmpArr = url.Split("_");
var fileName = tmpArr.AsQueryable().Last(); ;
FileStream fs = new FileStream( filePath, FileMode.OpenOrCreate);
fs.Close();
return File(new FileStream(filePath, FileMode.Open), "application/octet-stream", fileName);
}
方法二:
strFileName这个是下载下来的文件显示的名称,strToPath + targetFileName 这个是文件所在路径及其物理文件名(一般是字母加数字组合起来的)
调用:WebFile.downloadByStream(Response, strFileName, strToPath + targetFileName);
public static void downloadByStream(HttpResponse Response, string fileName, string filePath)
{
if (File.Exists(filePath))
{
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
浙公网安备 33010602011771号