我有一个应用程序,允许管理员上传商店的图像。 Currenly它使用服务器路径在本地工作:
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/Images/"+ImageName); //which is local project folder.
但是,当我发布它时,它不再显示上传的图像或上传。如何更改要在服务器上存储的服务器路径,例如,如果站点地址是www.google.com,是否有办法从服务器而不是本地进行此操作?
以下是完整的图片上传代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CustomerID,DiscountLevelID,LoyaltyLevelID,CustomerCompanyName,CustomerName,CustomerSurname,CustomerGUID,CustomerStatus,CustomerAddress,CustomerTel,CustomerCel,CustomerNumber,CustomerContact,CustomerLogo,CustomerLogoPath,LastStoreCustomerSyncID")] Customer customer, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/Images/");
if (!Directory.Exists(physicalPath))
Directory.CreateDirectory(physicalPath);
string physicalFullPath = Path.Combine(physicalPath, ImageName);
file.SaveAs(physicalFullPath);
customer.CustomerLogo = ImageName;
customer.CustomerLogoPath = physicalFullPath;
db.Customers.Add(customer);
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(customer);
}
使用它在索引中显示图像:
<td><img src=@Url.Content(@item.CustomerLogo) width="100" height="100" /></td>
答案 0 :(得分:0)
要查看图片,您可以尝试这样:
<img src= "@Url.Content(@Model.CustomerLogo)" alt="Image" width="100" height="100" />
@Url.Content
接受相对路径。
要上传图片,您可以尝试这样:
<强>型号:强>
public class FileModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
查看:
@model MvcApplication.Models.FileModel
@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
@Html.LabelFor(x => x.File)
@Html.TextBoxFor(x => x.File, new { type = "file" })
@Html.ValidationMessageFor(x => x.File)
</div>
<button type="submit">Upload</button>
}
<强>控制器:强>
public ActionResult Upload(FileModel model)
{
string fileName = Path.GetFileName(model.File.FileName);
string path = Server.MapPath("~/Files/");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string fullPath = Path.Combine(path, fileName);
model.File.SaveAs(fullPath);
return View();
}