天天看點

asp.net mvc實作檔案下載下傳

前段時間一直對如何解決檔案下載下傳的問題比較困惑,對檔案下載下傳的問題一直都是用的前端的方式解決的,代碼如下

//下載下傳
function download(filePath) {
    window.open(filePath);
}
           

但是這個方法有他的缺陷:

1.下載下傳的檔案字尾必須為iis程式池中存在的檔案

2.此方法是通過浏覽器打開伺服器檔案,無法直接下載下傳

近期看了asp.net 下載下傳檔案幾種方式這篇文章并且結合了一些其他的文章之後,找到了更好的解決辦法,我用的是 以字元流的形式下載下傳檔案

Controller源碼:

[HttpGet]
public ActionResult Download(string filePath) {
    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();
}
           

View源碼:

//下載下傳
function download(getur) {
            //getur = "/控制器/方法名?filePath=" + 檔案相對路徑;
            var str = document.createElement("a");//建立a标簽
            str.href = getur;
            document.body.appendChild(str);
            str.click();
            str.style.display = "none";//隐藏标簽
            //ps:本想删除a标簽,但是沒找到好用的方法,隻能暫時先隐藏掉
}
           

效果圖:

asp.net mvc實作檔案下載下傳