Web 端異步下載文件
- 實現文件異步下載;
- 在服務端無法返回文件,或發生異常時給予提示。
JavaScript:
服務端返回的JSON對象形如:
{
code:200,
msg:'下載成功|未找到指定文件',
filePath:'/file/test.txt'
}
function downloadFile() {
var url = 'api/download';
var params = {...};
$.ajax({
type:'GET',
url:url,
data:params,
dataType:'json',
success:function(data){
if(data.code == 200){
//直接跳轉到返回的文件路徑
window.location.href = data.filePath;
} else {
//無法下載時, 提示
alert(data.msg);
}
},
error:function(xhr, s, e){
alert('請求錯誤');
}
})
}
Web API
[HttpGet]
public IHttpActionResult Download(string file)
{
if(string.IsNullOrWhiteSpace(file))
return Json(new { Code = 3, Msg = '文件名不允許為空' });
try
{
//檢查是否有權限下載文件...
//查找文件...
//生成文件臨時路徑...
//等等..
return Json(new { Code = 200, Msg = '可成功下載', FilePath = '/file/test.txt' });
}
catch (Exception ex)
{
Log.Error(ex);
return Json(new { Code = 500, Msg = '服務器內部出現異常' });
}
}
