文件上传到 ASP.NET Core 中的 wwwroot 文件夹

为什么我的以下代码有时会起作用,但有时却不起作用?


 private bool UploadFile(IFormFile ufile, string fname)

 {

     if (ufile.Length > 0)

     {

          string fullpath = Path.Combine(_env.WebRootPath, fname);

          using (var fileStream = new FileStream(fullpath, FileMode.Create))

          {

               ufile.CopyToAsync(fileStream);

          }

          return true;

     }

     return false;

 }

该代码确实设法将图片保存到我在下创建的文件夹中wwwroot,但图片没有出现,甚至在 Visual Studio 中也是如此。


有没有办法解决它?


谢谢。


即使我打开存储图片的文件夹的文件资源管理器,图片就像在那里但没有显示任何图像。


一只甜甜圈
浏览 445回答 3
3回答

一只萌萌小番薯

尝试如下。文件将上传到images文件夹下的wwwroot文件夹。private async Task<bool> UploadFile(IFormFile ufile){&nbsp; &nbsp; &nbsp;if (ufile != null && ufile.Length > 0)&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var fileName = Path.GetFileName(ufile.FileName);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images", fileName);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; using (var fileStream = new FileStream(filePath, FileMode.Create))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; await ufile.CopyToAsync(fileStream);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return false;}

MMTTMM

点网核心有同样的问题,这就是我所做的:-制作虚拟目录- 将其映射到该文件夹路径(在 wwwroot 内)- 使您fullpath与此 VD 相等;绝对路径(可以保存在配置文件中)- 将此文件夹的写入权限授予 iisuser

慕尼黑的夜晚无繁华

允许访问静态文件,只需在配置方法下的 startup.cs 文件中添加这一行:app.UseStaticFiles();
打开App,查看更多内容
随时随地看视频慕课网APP