- 实现文件异步下载;
- 在服务端没法返回文件,或发生异常时给予提示。
服务端返回的JSON
对象形如:javascript
{ 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('请求错误'); } }) }
[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 = '服务器内部出现异常' }); } }