[TOC]javascript
上傳文件我使用的是Bootstrap的插件FileInput,這個抽時間看看寫個博客html
如今下載我遇到坑了,而這個坑,我之前踩過.....java
網上一搜,大把,下面的代碼也是我複製網上的,怎麼都不行ajax
FileInfo fileInfo = new FileInfo("C:\\Users\\Justin\\Desktop\\學習\\20190528102940089.pdf"); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "attachment;filename=" + "20190528102940089.pdf"); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/octet-stream"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.WriteFile(fileInfo.FullName); Response.Flush(); Response.End();
而後我新建了個項目,把上面的代碼複製進去,行了.....json
我對比了一下個人項目,我竟然又犯了之前踩過的一個坑,我不知道ajax不能請求下載方法!!!app
ajax的返回值類型是json,text,html,xml類型,因此ajax請求的方法返回的基本上都是json格式,然而我訪問的是下載方法,返回的是文件流......學習
改版思路,使用ajax獲取文件的路徑,而後使用window.open打開,這裏又遇到一個問題,window.open不能打開本地路徑,好比D盤下的某個文件,由於js是拒絕訪問磁盤的,那就換成網站路徑咯網站
var curWwwPath = window.document.location.href; var pathName = window.document.location.pathname; var pos = curWwwPath.indexOf(pathName); var localhostPaht = curWwwPath.substring(0, pos); //這個localhostPaht就是你的網站的網址 //而後在ajax的success方法裏面直接打開 window.open(localhostPaht + data.ReturnData.filePath);
這裏的ReturnData就是一個json返回類,能夠攜帶一些Model類,以下spa
using System; using System.Collections.Generic; using System.Text; namespace test.Model { public enum ReturnStatus { FAILED=0, SUCCEED =1, WARNNING=2 } /// <summary> /// 返回信息提示 /// </summary> public class ReturnValue { public ReturnValue() { } public ReturnValue(ReturnStatus status, object returnData, string message) { Status = status; ReturnData = returnData; Message = message; } public ReturnValue(ReturnStatus status, string message) { Status = status; Message = message; } /// <summary> /// 默認失敗 /// </summary> /// <param name="result"></param> public ReturnValue(string message) { Status = ReturnStatus.FAILED; Message = message; } /// <summary> /// 狀態 /// </summary> public ReturnStatus Status { get; set; } /// <summary> /// 數據對象 /// </summary> public object ReturnData { get; set; } /// <summary> /// 接口訪問錯誤的時候返回的錯誤提示文字,訪問成功的時候爲空字符串 /// </summary> public string Message { get; set; } = ""; } }
Controller返回也很簡單插件
return Json(new ReturnValue(ReturnStatus.SUCCEED, new { filePath= filePath }, "下載成功"), JsonRequestBehavior.AllowGet);