当我尝试从列表上传文件时,我会收到这个错误
"错误:没有ID为1的文件。文件列表可能已经改变";
当我附加一个文件时它可以工作,但当列表有多个文件时,我会得到错误
我用来发送的电话是
调用功能
foreach (var item in fileList)
{
var Enow = item.GetMultipleFiles();
foreach (var _item in Enow)
{
output = await _IfileUpload.Upload(_item, NewGuid.ToString());
}
}
调用函数
public async Task<string> Upload(IBrowserFile entry, string UploadGuid)
{
try
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "Uploads/" + UploadGuid, entry.Name);
var _path = Path.Combine(Directory.GetCurrentDirectory(), "Uploads/" + UploadGuid);
if (!Directory.Exists(_path))
{
System.IO.Directory.CreateDirectory(_path);
}
Stream stream = entry.OpenReadStream();
FileStream fs = File.Create(path);
await stream.CopyToAsync(fs);
stream.Close();
fs.Close();
return path;
}
catch (Exception ex)
{
throw ex;
}
}
BlazorInputFile导致错误:"不存在ID为"1"的文件;。在重新添加新文件时,不会保存属于以前文件的所有以前创建的对象。同时,索引从不再存在的未保存对象开始。在每个选择步骤保存文件都会给出正确的索引。调试器内部的Chrome表示inputfile.js 存在问题
我遇到了类似的问题,解决方案是创建图像数据列表,每次从浏览器添加新文件时都会填充该列表。在这种情况下,您可以正确掌握数据
private List<byte[]> _imageData = new List<byte[]>();
private void UploadFiles(InputFileChangeEventArgs e)
{
foreach (var file in e.GetMultipleFiles())
{
_files.Add(file);
_imageData.Add(GetImageBytes(file).Result);
}
}
private async Task<byte[]> GetImageBytes(IBrowserFile file)
{
var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
await using var fileStream = new FileStream(path, FileMode.Create);
await file.OpenReadStream(file.Size).CopyToAsync(fileStream);
var bytes = new byte[file.Size];
fileStream.Position = 0;
await fileStream.ReadAsync(bytes);
fileStream.Close();
File.Delete(path);
return bytes;
}
最后是
if (_imageData != null && _imageData.Count() > 0)
{
foreach (var photo in _imageData)
{
var result = await _uploadService.UploadImage(photo);
}
}
我会从[docs][1]
中尝试这个样本
<h3>Upload PNG images</h3>
<p>
<InputFile OnChange="@OnInputFileChange" multiple />
</p>
@if (imageDataUrls.Count > 0)
{
<h4>Images</h4>
<div class="card" style="width:30rem;">
<div class="card-body">
@foreach (var imageDataUrl in imageDataUrls)
{
<img class="rounded m-1" src="@imageDataUrl" />
}
</div>
</div>
}
@code {
IList<string> imageDataUrls = new List<string>();
private async Task OnInputFileChange(InputFileChangeEventArgs e)
{
var maxAllowedFiles = 3;
var format = "image/png";
foreach (var imageFile in e.GetMultipleFiles(maxAllowedFiles))
{
var resizedImageFile = await imageFile.RequestImageFileAsync(format,
100, 100);
var buffer = new byte[resizedImageFile.Size];
await resizedImageFile.OpenReadStream().ReadAsync(buffer);
var imageDataUrl =
$"data:{format};base64,{Convert.ToBase64String(buffer)}";
imageDataUrls.Add(imageDataUrl);
}
}
}