Reputation:
I have an application that allows the admin to upload Images for a store. Currenly it works locally using server path :
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/Images/"+ImageName); //which is local project folder.
When I publish it however, it no longer displays the uploaded image or uploads. How do I change the server path to store on the server, for example if the site address is www.google.com , is there a way to make this work from the server and not just locally?
Here is the full Image Upload code:
[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);
}
Using this to display the image in Index:
<td><img [email protected](@item.CustomerLogo) width="100" height="100" /></td>
Upvotes: 0
Views: 1851
Reputation: 5331
To view image, you can try like this:
<img src= "@Url.Content(@Model.CustomerLogo)" alt="Image" width="100" height="100" />
@Url.Content
accepts relative path.
To upload image, you can try like this:
Model:
public class FileModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
View :
@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>
}
Controller:
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();
}
Upvotes: 2