Web 端异步下载文件

Web 端异步下载文件

  1. 实现文件异步下载;
  2. 在服务端无法返回文件,或发生异常时给予提示。

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 = '服务器内部出现异常' });
        }
    }
原文地址:https://www.cnblogs.com/aning2015/p/9353501.html