卡了好久,總算好啦。
頁面地址和服務器下載文件地址不是一個。所以 使用a 標籤的時候,點擊下載谷歌瀏覽器沒有反應,360瀏覽器可以。
查了好久的資料,原來是跨域啥啥的,,,,,,。
好吧,不能用a標籤,那就改用字節流模式下載。
前端
get(url, param1) {
console.log('url= ' + url + '\n ' + param1);
return axios({
method: 'get',
url: url + '?'+'token=' + api.http_token + '&httpdata=' + param1,
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
responseType:'blob'
})
.then((response) => {
console.log(response);
var res = checkStatus(response);
return res;
})
.then((res) => {
return checkCode(res);
});
}
responseType:'blob' 這句很重要,不加上,服務器端返回的是亂碼哦。
前端下載
-- 1、發起請求
let postdata = '';
postdata =
'{"file_src":"' + temp_src + '","file_name":"' + temp_filename + '"}';
postdata = base_encode(postdata);
let that = this;
this.$get(
api.http_downfile,
postdata
).then(res => {
that.saveFile(res, temp_filename);
});
-- 下載文件
saveFile: function(data, fileName) {
var export_blob = new Blob([data]);
var save_link = document.createElement('a');
document.body.appendChild(save_link);
save_link.style.display = 'none';
var urlObject = window.URL.createObjectURL(export_blob);
save_link.href = urlObject;
save_link.download = fileName;
save_link.click();
document.body.removeChild(save_link);
},
服務器端 C# IIS
[WebMethod(Description = "直接下載文件")]
public void DownLoadFile(string token, string httpdata)
{
string ht = String.Empty;
ht = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(httpdata));
Com_Json udao = new Com_Json();
Com_Json.FileData tsd = new Com_Json.FileData();
tsd = udao.GetFileData(ht);
string fullpath = tsd.file_src;
string filename = tsd.file_name;
//以字符流的形式下載文件
FileStream fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] fileBuffer = new byte[(int)fs.Length];
fs.Read(fileBuffer, 0, fileBuffer.Length);
long fileSize = fs.Length;
fs.Close();
Context.Response.Charset=("utf-8");
Context.Response.ContentType = "application/octet-stream";
//通知瀏覽器下載文件而不是打開
Context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ";");
Context.Response.AddHeader("Content-Length", fileSize.ToString());
//瀏覽器默認使用碼錶gb2312來展示數據,因此會出現亂碼。
Context.Response.BinaryWrite(fileBuffer);
Context.Response.Flush();
Context.Response.End();
}