I have a website that shows galleries, users can upload their own content from the web (by entering a URL) or by uploading a picture from their computer.
I am storing the URL in the database which works fine for the first case but I need to figure out where to store the actual images if a user uploads pictures from their local computer.
Is there any recommendation here or best practice on where should I store these and how can i store it on server?
help me! thank you very much
You can follow these steps, for uploading user pictures on the server
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" })
{
<input type="file" name="ImageFile" id="ImageFile" />
<input type="submit" value="Submit" id="Submit" />
}?
[HttpPost]
public ActionResult ImageUpload()
{
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
var savedurl = "";
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
string subPath = "~/Images/Upload/"; // your code goes here
bool exists = System.IO.Directory.Exists(Server.MapPath("~/Images/Upload/"));
if (!exists)
{ System.IO.Directory.CreateDirectory(Server.MapPath("~/Images/Upload/")); }
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Images/Upload/"), fname);
savedurl = "/Images/Upload/" + file.FileName;
//save this URL in database here
//save file on server
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json(new { MSG="File Uploaded Successfully!" , SAvedUrl= savedurl },JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return View("_Error");
}
}
else
{
return View("_Error");
}
}
If you want to use any plugin like Dropzone JS for drag and drop feature you can check this article
https://qawithexperts.com/article/asp.net/file-uploading-using-dropzone-js-html5-in-mvc/81
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly