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

最近在項目中,實現web api文件下載功能。前端

文件是存儲於數據庫中。web

文件內容是vbinary數據類型,固然數據類型爲image也沒有問題的。數據庫

參考下面代碼示例:json

 

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
 [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

 

而後,前端是呼叫接口:api

 

 

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
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

 

效果:app

相關文章
相關標籤/搜索