如何在处理图片前确保上传完成

How to ensure upload is completed before processing image

我正在尝试上传图像文件,然后在上传完成后对其进行处理。在开始处理之前如何确保上传已完成?我的示例代码如下:

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 电话的情况下执行此操作。

我在 运行 时间

收到以下错误

The process cannot access the file 'C:\Users\Roger\Documents\ScratchPad\src\Web\wwwroot\images\arrivals\test.jpg' because it is being used by another process.

文件被锁定,因为您没有关闭之前用于创建文件的流。

确保处理之前的流以确保所有数据都写入其中并释放文件。

您可以通过将流包装在 using 语句中来做到这一点。

//...

using(var stream = new FileStream(filePath, FileMode.Create)) {
    await EmployeeForCreation.Photo.CopyToAsync(stream);
}

ProcessImage(filePath, height: 100);

//...