为什么当我将图像复制到文件夹 wwwroot/images/ 时,我可以在 img html 标签中显示图像,而当我通过此代码保存图像时,图像不显示?
if (image.ImageFile != null)
{
string result = Path.GetRandomFileName();
var r = result.Replace('.', '3');
string path = @"\\wwwroot\\images\\" + r + "\\";
string imageName = Path.GetFileName(image.ImageFile.FileName);
string folderPath = Path.Combine(_env.ContentRootPath + path);
Directory.CreateDirectory($"{folderPath}");
var filePath = Path.Combine(folderPath + imageName);
using (var stream = System.IO.File.Create(filePath))
{
image.ImageFile.CopyToAsync(stream);
}
product.FirstImageSrc = "images/"+ r+ "/" + imageName; }
文件已创建,但大小为 0B
经过测试,我想我已经找到了问题所在。
image
中的image.ImageFile.CopyToAsync(stream);
应该是一个对象(您的自定义对象)。您应该先保存文件。
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IWebHostEnvironment _env;
public HomeController(ILogger<HomeController> logger, IWebHostEnvironment env)
{
_logger = logger;
_env = env;
}
[HttpPost("UploadImage")]
public async Task<IActionResult> UploadImage(IFormFile imageFile)
{
if (imageFile == null || imageFile.Length == 0)
{
return BadRequest("The file is empty.");
}
try
{
string randomFolderName = Path.GetRandomFileName().Replace('.', '3');
string folderPath = Path.Combine(_env.WebRootPath, "images", randomFolderName);
Directory.CreateDirectory(folderPath);
string imageName = Path.GetFileName(imageFile.FileName);
string filePath = Path.Combine(folderPath, imageName);
// also works for me
//using (var stream = new FileStream(filePath, FileMode.Create))
//{
// await imageFile.CopyToAsync(stream);
//}
using (var stream = System.IO.File.Create(filePath))
{
// should add await
imageFile.CopyToAsync(stream);
}
string relativePath = $"images/{randomFolderName}/{imageName}";
return Ok(new
{
Message = "upload successfully",
FilePath = relativePath
});
}
catch (Exception ex)
{
return StatusCode(500, new
{
Message = "Upload failed",
Error = ex.Message
});
}
}