[英]how to upload multiple images with progress bar in asp .net mvc 4 with razor?
[英]How to upload images to folder under wwwroot in .NET? (MVC)
我正在嘗試將圖像文件保存到wwwroot下的文件夾中,數據庫應存儲文件的路徑名,而wwwroot下的文件夾應存儲圖像文件。
我要實現的是將圖像文件保存到wwwroot下的文件夾中。 以及要保存到本地數據庫的圖像文件的路徑名。
謝謝!!
視圖:
<form asp-controller="MobileSuits" asp-action="Add">
<div class="form-horizontal">
<h4>TheMobileSuit</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Id" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Name" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="PicFile" class="col-md-2 control-label"></label>
<div class="col-md-10">
@*<input type="file" name="photo"
class="form-control" />*@
<input type="file" name="file" id="file" />
<span asp-validation-for="PicFile" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
控制器:
[Authorize]
public IActionResult Add()
{
return View();
}
[Authorize]
[HttpPost]
public IActionResult Add(TheMobileSuit themobilesuits, IFormFile photo)
{
DbSet<TheMobileSuit> dbs = _dbContext.TheMobileSuit;
dbs.Add(themobilesuits);
if (_dbContext.SaveChanges() == 1)
TempData["Msg"] = "New Order Added!";
else
TempData["Msg"] = "Error.";
return RedirectToAction("Index");
}
First step would be create folder under wwwroot if it doesn't exists
1. Directory.CreateDirectory(_hostingEnvironment.WebRootPath + "\\folderName\\");
Second step would be append your file name to above path like below
2.`var fullPathName = _hostingEnvironment.WebRootPath + "\\folderName\\" +
photo.file.FileName;`
Final step would be by using FileStream you can copy the file
3.`using (FileStream stream = System.IO.File.Create(fullPathName))
{
photo.file.CopyTo(stream);
stream.Flush();
}`
試試這個簡單。 在這種情況下,您必須注入_hostingEnvironment
以便獲得ContentRootPath
string folderName = "Upload/Profile/" + user.Id;
string webRootPath = _hostingEnvironment.ContentRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
string extention = file.ContentType.Split("/")[1];
string fileName = user.Id + ".jpg";
string fullPath = Path.Combine(newPath, fileName);
string envpath = folderName + "/" + fileName;
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.