我正在上傳影像作為用戶模型的一部分,我應該保存影像 url 以在 REST 客戶端中顯示影像(鏈接如“localhost/Images/ImageName.png”),所以我將影像保存在wwwroot 這個在 Post Api 中:
[HttpPost]
public async Task<String> Post([FromForm]Machine mach)
{
try
{
if (mach.Files.Length > 0)
{
{
FileInfo fi = new FileInfo(mach.Files.FileName);
var newfilename = "Image_" DateTime.Now.TimeOfDay.Hours fi.Extension;
var path = Path.Combine(hostingEnvironment.WebRootPath "\\Images\\" newfilename);
/* var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Images");*/
using (var stream = new FileStream(path, FileMode.Create))
{
mach.Files.CopyTo(stream);
}
Machine machine = new Machine();
mach.ImagePath = path;
_context.machines.Add(mach);
_context.SaveChangesAsync();
}
return ("saved");
}
我正確保存了模型,但我得到了這樣的網址:
"imagePath": "C:\Users\amyra\source\repos\MyApi\wwwroot\Images\Image_18.png"
我試圖通過“localhost:port/Images/..”顯示影像,但找不到頁面。
uj5u.com熱心網友回復:
檢查您的應用程式的啟動并確保該app.UseStaticFiles();行在那里。通常它應該在之后app.UseHttpsRedirection();和之前app.UseAuthorization
默認 API 模板沒有此行。
編輯: 保存影像的 URL 而不是物理檔案路徑
mach.ImagePath = new UriBuilder
{
Scheme = Request.Scheme,
Host = Request.Host.Host,
Port = Request.Host.Port ?? -1,
Path = "/Images/" newfilename
}.ToString();
雖然我不建議將 URL 的主機/埠/方案部分保存在資料庫中,因為這些可能會發生變化。
相反,我建議只保存路徑部分
mach.ImagePath = "/Images/" newfilename;
您可以在向客戶端提供資料時添加主機/埠/方案部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490302.html
標籤:网 asp.net-mvc asp.net 核心
