Mar*_*lPT 2 .net c# upload image
我正在将图像上传到我的应用程序,并使用以下代码:
public static async Task<string> GetThumbnailAndImage(InputFileChangeEventArgs e)
{
var file = e.File;
var imageTmp = await file.RequestImageFileAsync("jpg", 200, 200);
return image = await UploadMedia(imageTmp);
}
public static async Task<string> UploadMedia(IBrowserFile file)
{
byte[] bytes = new byte[file.Size];
var stream = file.OpenReadStream(int.MaxValue);
await stream.ReadAsync(bytes);
return Convert.ToBase64String(bytes);
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是,根据我要求的像素,图像被部分上传,例如:
我期待左边的图像,但得到右边的图像。有谁知道可能导致这个问题的原因是什么?
最好的
@TLP 答案解决了问题,但如果我们遵循 Microsoft 安全建议,在上传时不将文件读入内存,它仍然可以得到改进:https ://learn.microsoft.com/en-us/aspnet/core/blazor/file-上传?view=aspnetcore-6.0&pivots=server
因此,解决此问题的正确方法是将文件存储在临时文件中,并将其转换为字节数组后,关闭文件流并删除 tmp 文件:
public static async Task<string> UploadMedia(IBrowserFile file)
{
var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
await using var fs = new FileStream(path, FileMode.Create);
await file.OpenReadStream(file.Size).CopyToAsync(fs);
var bytes = new byte[file.Size];
fs.Position = 0;
await fs.ReadAsync(bytes);
fs.Close();
File.Delete(path);
return Convert.ToBase64String(bytes);
}
Run Code Online (Sandbox Code Playgroud)