• 下载文件(API接口,Angularjs前端)


    最近在项目中,实现web api文件下载功能。

    文件是存储于数据库中。

    文件内容是vbinary数据类型,当然数据类型为image也没有问题的。

    参考下面代码示例:

     [HttpPost]
            public async Task<HttpResponseMessage> DownloadFile(JObject jObj)
            {
                var jsonStr = JsonConvert.SerializeObject(jObj);
                var jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonStr);
    
                BarCode bc = new BarCode();
                bc.BarCode_nbr = jsonParams.BarCode_nbr;
    
                BarCodeEntity bce = new BarCodeEntity();
                var barcode = bce.BarCodes(bc).FirstOrDefault();
    
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
    
                string physicalPath = HttpContext.Current.Server.MapPath("~/Temp/") + barcode.FileName;
    
                byte[] buffer = (byte[])barcode.QrCode;
    
                if (!File.Exists(physicalPath))
                {
                    using (FileStream fileStream = File.Create(physicalPath))
                    {
                        fileStream.Write(buffer, 0, buffer.Length);
                    }
                }
    
                response.Content = new ByteArrayContent(buffer);
                response.Content.Headers.ContentLength = buffer.LongLength;
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = barcode.FileName;
                response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(barcode.FileName));
                return await Task.FromResult(response);
            }
    Source Code

    然后,前端是呼叫接口:

    var arg = {};
                arg.BarCode_nbr = qr.BarCode_nbr;
    
                fetch('/api/IoSvc/DownloadFile', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(arg),
                })
                    .then(res => res.blob())
                    .then(data => {
                        let blobUrl = window.URL.createObjectURL(data);
                        const a = document.createElement('a');
                        a.style.display = 'none';
                        a.download = qr.FileName;
                        a.href = blobUrl;
                        a.click();
                    });
    Source Code

    效果:

  • 相关阅读:
    MySQL 常用到的几个字符处理函数
    MySQL DATE_SUB查询工龄大于35的员工信息
    Mysql 没有nvl()函数,却有一个类似功能的函数ifnull();
    switch 循环中的case理解
    批处理系统和分时系统各具有什么特点?为什么分时系统的响应比较快?
    存储式计算机的主要特点是什么?
    代码实现导航栏分割线
    Keras函数式API介绍
    Keras通过子类(subclass)自定义神经网络模型
    R语言kohonen包主要函数介绍
  • 原文地址:https://www.cnblogs.com/insus/p/13521726.html
Copyright © 2020-2023  润新知