[英]Asp.net Core File Upload
當我保存圖像時,圖像成功保存到數據庫中,但是它需要完整的圖像路徑,例如C:\\ Users .... \\ Uploads \\ employee.jpg我不想要這樣,我需要以某種方式保存圖像路徑〜Uploads \\ employee.jpg以及特定的文件夾和相同的路徑應該保存在數據庫中,如果有人在保存正確的路徑后向我顯示我如何查看該圖像。 因為這個我有錯誤:
“不允許加載本地資源:file:/// C:/ ......”
謝謝!
我的代碼:
[HttpPost]
public async Task<IActionResult> Create(Photos photos)
{
if (ModelState.IsValid)
{
var filePath =
Path.Combine(_appEnvironment.ContentRootPath,
"Uploads", photos.FormFile.FileName);
photos.PhotoPath = filePath;
using (var stream = new FileStream(filePath, FileMode.Create))
{
await photos.FormFile.CopyToAsync(stream);
}
_context.Add(photos);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["NewsId"] = new SelectList(_context.News, "NewsId",
"NewsBigTitle", photos.NewsId);
return View(photos);
}
分解代碼:
var localPath = Path.Combine("Upload", "file.jpg");
var fullPath = Path.Combine(_appEnvironment.ContentRootPath, localPath);
將localPath
保存到PhotoPath
編輯
Okey,現在在視圖中顯示您的PhotoPath
,並將其定位為文件流操作。
[HttpGet("path/{image}")]
public FileStreamResult Image(string image)
{
var result = new FileStreamResult(new FileStream(
Path.Combine(_appEnvironment.ContentRootPath, image),
FileMode.Open,
FileAccess.Read), "image/<your_mime>");
return result;
}
我認為最好的方法是使用以下格式http://example.com/path/image.jpg
創建新字符串並將其綁定到src
。
您不能使用以下內容來定位動態添加的文件: ~/path/image.jpg
作為源。
確保已配置IFileProvider
使其指向Startup
類的Configure
方法中的Uploads
文件夾:
app.UseStaticFiles(); // Default one
// Adding one more location - folder named `Uploads` to be a custom static files folder.
// The `Uploads` folder is available in the content root directory of the application (where your `Controllers` folder.
// You can point it of course inside `wwwroot` - use `env.WebRootPath` instead)
app.UseStaticFiles(new StaticFileOptions {
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Uploads")),
RequestPath = new PathString("/Uploads")
});
完成此操作后,您應該可以在控制器操作中以這種方式上傳文件:
var filePath = Path.Combine(_environment.ContentRootPath, "Uploads", photos.FormFile.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await photos.FormFile.CopyToAsync(stream);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.