【发布时间】:2020-02-10 22:39:36
【问题描述】:
在我的 Blazor 应用程序中,我有一个 wwwroot/upload 文件夹,我想在其中上传图像。但是图像永远不会进入目录。
我的代码 -
async Task UploadFile()
{
if (file != null)
{
// Just load into .NET memory to show it can be done
// Alternatively it could be saved to disk, or parsed in memory, or similar
var ms = new System.IO.MemoryStream();
await file.Data.CopyToAsync(ms);
status = $"Finished loading {file.Size} bytes from {file.Name}";
// TODO: Need to upload the file to wwwroot/upload
var content = new MultipartFormDataContent {
{ new ByteArrayContent(ms.GetBuffer()), "\\upload\\", file.Name }
};
await Http.PostAsync("api/Blog/UploadFeaturedImage", content);
}
}
为什么文件没有到达目的地?
更新
我的 api/Blog/UploadFeaturesImage 在下面,我相信问题出在此处。它将所有文件上传到 API 项目中名为 Upload 的文件夹中。请问如何告诉它上传到 wwwroot/upload?
[Authorize]
[HttpPost("[action]")]
public async Task UploadFeaturedImage()
{
if (HttpContext.Request.Form.Files.Any())
{
foreach (var file in HttpContext.Request.Form.Files)
{
var path = Path.Combine(Environment.CurrentDirectory, "upload", file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
}
【问题讨论】:
-
控制台日志有错误吗?
-
你如何处理“api/Blog/UploadFeaturedImage”上的文件?
-
@aguafrommars 现在我添加了 api 代码,我可以看到问题,它上传到服务器项目上的文件夹,而不是 Blazor 客户端项目。我可以在那里的上传文件夹中看到上传。我将如何指定 wwwroot 文件夹而不是服务器文件夹?
-
通过自定义其路径,但在 Prod 环境中,您是否将为您的 blazor 应用程序创建一个文件夹?我猜没有。
-
@aguafrommars 可能不是。实现这一目标的最佳方法是什么?将图像存储在服务器上的位置是有意义的,但是当我需要在 Blazor 应用程序中显示图像时如何引用它?
标签: blazor