我正在尝试上传图像文件,然后在完成上传后对其进行处理。在开始处理之前,如何确保上传已完成?我的示例代码如下:
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
if (EmployeeForCreation.Photo != null)
{
var arrivalsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images", "arrivals");
var filePath = Path.Combine(arrivalsFolder, EmployeeForCreation.Photo.FileName);
await EmployeeForCreation.Photo.CopyToAsync(new FileStream(filePath, FileMode.Create));
//How to ensure that previous procedure has been completed before this procedure starts
ProcessImage(filePath, height: 100);
}
return RedirectToPage("./Details");
}
return Page();
}
public void ProcessImage(string filePath, int height)
{
string rootDirectoryPath = new DirectoryInfo(filePath).Parent.Parent.FullName;
var processingPathDirectory = Path.Combine(rootDirectoryPath, Constants.PROCESSING_FOLDER);
using (Image<Rgba32> image = Image.Load(filePath))
{
image.Mutate(x => x
.Resize(image.Width / 2, image.Height / 2)
.Grayscale());
image.Save("processingPathDirectory/fb.png"); // Automatic encoder selected based on extension.
}
}
如果可能的话,我希望不进行ajax调用。
在运行时出现以下错误
该进程无法访问文件'C:\ Users \ Roger \ Documents \ ScratchPad \ src \ Web \ wwwroot \ images \ arrivals \ test.jpg',因为该文件正在被另一个进程使用。
答案 0 :(得分:1)
文件被锁定,因为您没有关闭用于创建文件的上一个流。
请确保处置上一个流,以确保所有数据都已写入其中并释放了文件。
您可以通过将流包装在using
语句中来做到这一点。
//...
using(var stream = new FileStream(filePath, FileMode.Create)) {
await EmployeeForCreation.Photo.CopyToAsync(stream);
}
ProcessImage(filePath, height: 100);
//...