我正在使用Magick.NET将PDF转换为PNG并通过ajax将其流回页面。
一直有效,直到PDF上传两次。尝试覆盖或删除现有文件时,调试器会告诉我该文件正被另一个进程使用。
这是我的函数,它将Image返回给控制器:
//path is a fully qualified path to a file ending in .PDF
private Image ConvertPDFTOneImage(string path)
{
MagickReadSettings settings = new MagickReadSettings();
settings.Density = new PointD(300, 300);
using (MagickImageCollection images = new MagickImageCollection())
{
FileInfo file = new FileInfo(path);
images.Read(file);
file = null;
using (MagickImage horizontal = images.AppendHorizontally())
{
string PNGName = Path.ChangeExtension(path, ".png");
horizontal.Write(PNGName);
}
return Image.FromFile(path.Replace("pdf", "png"));
}
}
我的控制器将响应流回浏览器:
public async Task<HttpResponseMessage> PostFormData([FromUri] int sellerID, [FromUri] int eventID, [FromUri] string section, [FromUri] string row, [FromUri] string seat)
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
try
{
string base64 = string.Empty;
SellerObjects.Externeal.SellerTicket TicketToSave = new SellerObjects.Externeal.SellerTicket();
TicketToSave.UploadedFile = HttpContext.Current.Request.Files["UploadedImage"];
SellerTicketRepo TheLocalSellerRepo = new SellerTicketRepo(TicketToSave);
using (MemoryStream ms = new MemoryStream())
{
TheLocalSellerRepo.GetConvertedPDFImage().Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
base64 = System.Convert.ToBase64String(ms.ToArray());
}
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StringContent(base64);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, "Error saving file.");
}
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "An error has occurred");
}
答案 0 :(得分:1)
我假设您要返回的Image类是System.Drawing.Image。您需要Dispose此对象以释放文件锁。
// Instead of this:
using (MemoryStream ms = new MemoryStream())
{
TheLocalSellerRepo.GetConvertedPDFImage().Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
base64 = System.Convert.ToBase64String(ms.ToArray());
}
// Should you be doing this:
using (MemoryStream ms = new MemoryStream())
{
using (Image img = TheLocalSellerRepo.GetConvertedPDFImage())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
base64 = System.Convert.ToBase64String(ms.ToArray());
}
}
// Or you could even do this (if GetConvertedPDFImage() returns a MagickImage):
using (MagickImage img = TheLocalSellerRepo.GetConvertedPDFImage())
{
img.Format = MagickFormat.Jpeg;
base64 = img.ToBase64();
}