我的 Blazor WASM 应用程序中有一个组件,它从用户那里获取签名并将其设为 png 文件。我从 JavaScript 组件获取字节并创建 MemoryStream。但是当我将其发送到后端时,我没有字节,即使它们位于前端。 我设置的方式对于文件上传来说效果很好。我正在另一个组件中执行此操作。这会获取一个 IBrowserFile,然后创建一个 MultipartFormDataContent 对象,并且顺利完成。但签名图像一路上丢失了字节。
以下是客户的方法:
private async Task SaveSignatureAsync(byte[] imageBytes)
{
var stream = new MemoryStream();
stream .Write(imageBytes, 0, imageBytes.Length);
var content = new MultipartFormDataContent();
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
var streamContent = new StreamContent(stream , Convert.ToInt32(stream .Length));
streamContent.Headers.ContentType = new MediaTypeHeaderValue("image/png");
content.Add(streamContent, "image", "signature.png");
_imageUrl = await PicUploadHttpRepository.UploadImage(content);
}
这是 HTTP 服务:
public async Task<string> UploadImage(MultipartFormDataContent content)
{
var response = await _httpService.PostForm(_apiUrl, content);
string jsonString = await response.GetBody();
if (!response.Success)
{
throw new ApplicationException(jsonString);
}
PicUploadResponse picUploadResponse = JsonSerializer.Deserialize<PicUploadResponse>(jsonString);
return picUploadResponse is not null ? picUploadResponse.FileURL : string.Empty;
}
public async Task<HttpResponseWrapper<object>> PostForm(string url, MultipartFormDataContent content)
{
var response = await httpClient.PostAsync(url, content);
return new HttpResponseWrapper<object>(null, response.IsSuccessStatusCode, response);
}
这是 API 端点:
[HttpPost, DisableRequestSizeLimit]
public async Task<IActionResult> UploadAsync()
{
try
{
var formCollection = await Request.ReadFormAsync();
var file = formCollection.Files.First();
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
// use guid for file name
var fileExtension = Path.GetExtension(fileName);
var blobFileName = $"{ Guid.NewGuid() }{ fileExtension.ToLower() }";
string fileURL = await uploadService.UploadAsync(file.OpenReadStream(), blobFileName, file.ContentType, _imageBlobContainerName);
return Ok(new { fileURL });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
我以与用户选择的 IBrowserFile 相同的方式进行设置。效果很好。但它不适用于 MemoryStream。请指教。 谢谢
旧帖子,但供将来参考。写入 MemoryStream 后,位置位于流的末尾,因此没有更多数据可用。
可以通过将位置设置为0来固定:
var stream = new MemoryStream();
stream.Write(imageBytes, 0, imageBytes.Length);
stream.Position = 0;