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);
}
});