我上传了azure上的asp.net MVC应用程序,它没有从服务器上的文件夹检索图像
问题描述:
我创建了一个ASP.NET MVC应用程序并上传到azure上,它的图像保存在一个文件夹内,并且它们在我的本地服务器。但是当我将我的网站上传到azure时,它不会显示我在线上传的图像,但会显示我已上传到本地服务器上的图像。将图像保存代码是首先如下我上传了azure上的asp.net MVC应用程序,它没有从服务器上的文件夹检索图像
public JsonResult MainCategoryImageUpload(CreateMainCategoryViewModel model)
{
var file = model.ImageFile;
string imgUrlWithoutTildSymbol = "";
if (file != null)
{
// save mainCategory Without Image
MainCategory m = new MainCategory();
m.DateCreated = DateTime.Now;
m.DateModified = DateTime.Now;
m.MainCategoryName = model.MainCategoryName;
ApplicationDbContext db = new ApplicationDbContext();
db.MainCategories.Add(m);
db.SaveChanges();
// Now lets save image for the above category
//var fileName = Path.GetFileName(file.FileName);
var extension = Path.GetExtension(file.FileName);
//var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file.FileName);
//var path = Path.Combine(Server.MapPath("~/Content/Images/UploadedImage/"), fileName);
//file.SaveAs(path);
string id_and_extension = m.MainCategoryId + extension;
string imgUrl = "~/Content/Images/MainCategories/" + id_and_extension;
m.ImageUrl = imgUrl;
db.Entry(m).State = EntityState.Modified;
db.SaveChanges();
file.SaveAs(Server.MapPath("~/Content/Images/MainCategories/" + id_and_extension));
imgUrlWithoutTildSymbol = "/Content/Images/MainCategories/" + id_and_extension;
}
return Json(imgUrlWithoutTildSymbol,JsonRequestBehavior.AllowGet);
}
答
,您可以使用Kudu console来检查目录/Content/Images/MainCategories/
是现有的。你可以remote debug your web app并检查代码是否按预期工作。
其次,我使用下面的代码来上传和显示图像,这可以在本地和Azure上正常工作,您可以参考它。
控制器
[HttpGet]
public ActionResult UploadFile()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
var path = Server.MapPath("~/Content/Images/MainCategories/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
file.SaveAs(path + fileName);
ViewBag.Message = "File Uploaded Successfully!!";
ViewBag.imgurl = "/Content/Images/MainCategories/" + fileName;
}
return View();
}
catch
{
ViewBag.Message = "File upload failed!!";
return View();
}
}
查看
@{
ViewBag.Title = "UploadFile";
}
<h2>UploadFile</h2>
@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { enctype="multipart/form-data"}))
{
<div>
@Html.TextBox("file", "", new { type= "file"}) <br />
<input id="Submit1" type="submit" value="submit" />
@ViewBag.Message
<img src="@ViewBag.imgurl" alt="" />
</div>
}
此外,Azure web app in an App Service plan has storage limit,如果可能的话,你可以存储在Azure Blob storage静态内容。
非常感谢,它为我工作 –
现在它工作正常,但一旦我重新发布我的网站,我在网上上传的以前的图片开始消失。意味着每次我重新发布网站时,前一个目录被删除/覆盖,并且变为空白。 –