c#服务端 AJAX下载二进制文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36535245/article/details/81197301

 写在vue初始化里的,也可以做js函数,因为jQuery的ajax不支持文件流返回

这是js获取文件流然后js处理下载

downloadFile: function (fileId, Name,type,DataVideoFileId) {
                    var _this = this;
                    var fileName = Name + "." + type;
                    var xhr = new XMLHttpRequest();    
                    xhr.open("get", 你的服务url, true);
                    xhr.responseType = "blob";
                    xhr.onload = function () {
                        if (this.status == 200) {
                            var blob = this.response;
                            if (window.navigator.msSaveOrOpenBlob) {
                                navigator.msSaveBlob(blob, fileName);
                            } else {
                                var link = document.createElement('a');
                                link.href = window.URL.createObjectURL(blob);
                                link.download = fileName;
                                link.click();
                                window.URL.revokeObjectURL(link.href);
                            }
                        }
                    }; xhr.send();
                }

后台c#服务端,首先根据url参数找到文件的路径,然后打开文件写入到Response

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="context"></param>
    /// <param name="userId"></param>
    /// <param name="id"></param>
    /// <returns></returns>
    public void DownloadFile(HttpContext context, string userId, long id)
    {
        try
        {
          //此处写你的逻辑得到文件地址,或者进行记录
               
            //以字符流的形式下载文件
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            context.Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            context.Response.AddHeader("Content-Disposition", "attachment;   filename=" + HttpUtility.UrlEncode(fileName +"."+ fileType, System.Text.Encoding.UTF8));
            context.Response.BinaryWrite(bytes);
        }
        catch (Exception ex)
        {
            LogHelper.WriteErrorLog(ex.ToString(), "PageError", "GerenVideo");
        }
        finally
        {
            context.Response.Flush();
            context.Response.End();
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_36535245/article/details/81197301
今日推荐