[英]Blazor WebAssembly PWA - IFormFile FromForm is always null
I have setup a Blazor WebAssembly ASP.Net Core hosted PWA
project and am using Azure Cognitive Services
in it.我已经设置了一个
Blazor WebAssembly ASP.Net Core hosted PWA
项目,并在其中使用Azure Cognitive Services
。 Therefore I have in one of my client-views a form where the user can upload an image and this will be referred to Azure.因此,我在我的一个客户端视图中有一个表单,用户可以在其中上传图像,这将被称为 Azure。
In the razor-view I have this:在剃刀视图中,我有这个:
@inject HttpClient client;
@inject IFileReaderService FileReader;
@inject NavigationManager navi;
<div class="text-center">
<input class="btn btn-secondary " name="file" @ref="InpReference" type="file" id="file-selector" placeholder="Brows" accept="image/*" capture="camera" @onclick="InputFile">
@if (_fileSelected != false)
{
<input class="btn btn-primary" type="button" role="button" id="startbutton" @onclick="Upload" value="upload" />
}
</div>
@code {
private async Task Upload()
{
// content base structure
MultipartFormDataContent content = new MultipartFormDataContent();
content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
foreach (/*IFileReference*/var fileReference in fileReferences)
{
Console.WriteLine("test1");
// getting the file size
IFileInfo fileinfo = await fileReference.ReadFileInfoAsync();
Stream fileStream;
var fileReferencesArray = fileReferences.ToArray();
using (var fs = await fileReference.CreateMemoryStreamAsync((int)fileinfo.Size))
{
Console.WriteLine("test2");
fileStream=new MemoryStream(fs.ToArray());
}
Console.WriteLine("test4" + fileinfo.Size);
StreamContent sc = new StreamContent(fileStream, (int)fileStream.Length);
content.Add(sc, "file", fileinfo.Name);
Console.WriteLine("test5");
}
Console.WriteLine("test6");
var response = await client.PostJsonAsync<List<Prediction>>("api/Azure/Prediction", content);
Console.WriteLine(response.Count + " : " + response.GetType().ToString());
foreach (var prediction in response)
{
Console.WriteLine(prediction.Id + ":" + prediction.Name + "," + prediction.Probability.ToString());
}
navi.NavigateTo("detailView/");
}
}
My WebApi Controller for the handling:我的 WebApi Controller 用于处理:
...
[HttpPost]
public List<Prediction> getPrediction([FromForm]IFormFile file)
{
if (file == null)
{
return new List<Prediction>();
}
List<Prediction> predicitions = azure_Client.GetPrediction(file.OpenReadStream());
return predicitions;
}
...
The problem is that the [FromForm]IFormFile file
in the controller is always null
.问题是 controller 中的
[FromForm]IFormFile file
始终为null
。 This is only null in the PWA
project.这只是
PWA
项目中的 null。 I have set the same project up without PWA
and it works , it is not null
and it is getting the selected image from the view!我在没有
PWA
的情况下设置了相同的项目并且它可以工作,它不是null
,它正在从视图中获取选定的图像! What is the difference there and why isn't the HttpClient
doing the same as in the Blazor WebAssembly ASP.Net Core hosted
?那里有什么区别,为什么
HttpClient
与Blazor WebAssembly ASP.Net Core hosted
中的做法不同?
According to my test, if you want to upload file in Blazor WebAssembly ASP.Net Core hosted PWA, please refer to the following steps根据我的测试,如果要在 Blazor WebAssembly ASP.Net Core 托管 PWA 中上传文件,请参考以下步骤
Client(I use the sdk Tewr.Blazor.FileReader
)客户端(我使用 sdk
Tewr.Blazor.FileReader
)
a.一个。 update
Program.cs
更新
Program.cs
builder.Services.AddFileReaderService(options => { options.UseWasmSharedBuffer = true; }); builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
b.湾。 upload file razor-view
上传文件razor-view
@using System.IO
@using Blazor.FileReader
@inject HttpClient client;
@inject IFileReaderService fileReader
<h1>File uplaod Blzaor WebAssembly!</h1>
<div class="row">
<div class="col-4">
<div class="form-group">
<input type="file" name="image" @ref="inputReference" @onchange="async() =>await OpenFile()" />
<ul>
<li>File Name: @fileName</li>
<li>Size: @size</li>
<li>Type: @type</li>
</ul>
</div>
<button class="btn btn-block btn-success" @onclick="async() =>await UploadFile()"> Upload File</button>
@if (!string.IsNullOrWhiteSpace(message))
{
<div class="alert alert-success">
File has been uplaoded
</div>
}
</div>
</div>
@code{
ElementReference inputReference;
string message = string.Empty;
string fileName = string.Empty;
string type = string.Empty;
string size = string.Empty;
Stream fileStream=null;
async Task UploadFile()
{
var content = new MultipartFormDataContent();
content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
var sc = new StreamContent(fileStream, (int)fileStream.Length);
content.Add(sc, "image", fileName);
var response = await client.PostAsync("/upload", content);
if (response.IsSuccessStatusCode) {
message = "OK";
}
}
async Task OpenFile()
{
var file = (await fileReader.CreateReference(inputReference).EnumerateFilesAsync()).FirstOrDefault();
if (file == null) {
return;
}
var fileInfo=await file.ReadFileInfoAsync();
fileName = fileInfo.Name;
type = fileInfo.Type;
size = $"{fileInfo.Size} Bytes";
using (var ms = await file.CreateMemoryStreamAsync((int)fileInfo.Size)) {
fileStream = new MemoryStream(ms.ToArray());
}
}
}
API COntroller API COntroller
[HttpPost]
public async Task<IActionResult> Post([FromForm(Name ="image")]IFormFile file) {
if (file == null || file.Length == 0) {
return BadRequest("do not receive file");
}
var fileName = file.FileName;
var extension = Path.GetExtension(fileName);
var newFileName = $"{Guid.NewGuid()}{extension}";
var filePath = Path.Combine(_env.ContentRootPath, "Images", newFileName);
if (!Directory.Exists(Path.Combine(_env.ContentRootPath, "Images"))) {
Directory.CreateDirectory(Path.Combine(_env.ContentRootPath, "Images"));
}
using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) {
await file.CopyToAsync(stream);
}
return Ok(filePath);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.