姿夏的海角
为钱做事,容易累;为理想做事,能够耐风寒;为兴趣做事,则永不倦怠

1. 将图片的路径转成流形式

public async Task<ByteArrayContent> GetPdf(long id)
        {
            try
            {
                var image = await AgentProxy.Instance.StockMaterialImageAgent.GetById(id);
                var filePath = image.FilePath;
                //ensure that the path is a correct path;
                if (!System.IO.File.Exists(filePath))
                    return new ByteArrayContent(new byte[] { });

                using (var fs = new FileStream(filePath, FileMode.Open))
                {
                    var content = new byte[fs.Length];
                    await fs.ReadAsync(content, 0, content.Length);
                    return new ByteArrayContent(content);
                }
            }
            catch (Exception exception)
            {
                Logger.WriteErrorLog(exception);
                return new ByteArrayContent(new byte[] { });
            }
        }

2.  补充头部信息

 [HttpGet]
        [AllowAnonymous]
        [Route("getPdf/{id}")]
        public async Task<HttpResponseMessage> GetPdf(long id)
        {
            var content = await stockTakeBusiness.GetPdf(id);
            var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            return result;
        }

3 请求

const getPdf = function (id) {
        const url = `${baseUrl}api/stockTake/getPdf/${id}`;
        return $http({
            url: url,
            responseType: "arraybuffer",
            method: "GET"
        });
    };

4 查看图片详情

let filePath = attachment.FilePath;
        $all.$stockTake.getPdf(attachment.Id)
            .then(function (response) {
                let type = "";
                let suffix = getFilePathSuffix(filePath);
                if (suffix.toLowerCase() == "pdf") {
                    type = 'application/pdf';
                } else {
                    type = `image/${suffix}`;
                }
                if (response.status === 200) {
                    var file = new Blob([response.data], {
                        type: type
                    });
                    var fileURL = URL.createObjectURL(file);
                    window.open(fileURL);
                }
            });   

  

posted on 2019-08-07 12:26  姿夏的海角  阅读(687)  评论(0编辑  收藏  举报