Upload multiple files ASP.NET MVC without AJAX

<form enctype="multipart/form-data" action="/SubmitImage"
         method="post" >
    <input type="file" name="photos" multiple />
    <input type="text" name="caption"/>
    <textarea name="description"></textarea>
    <input type="submit" value="Submit" />
</form>
[ValidateInput(false)]
[HttpPost]
public ActionResult SubmitImage(IEnumerable<HttpPostedFileBase> photos,
                                   FormCollection data)
{
    String authString = Request.QueryString["auth"].ToString();
 
    String caption = data["caption"].ToString();
    string description = data["description"].ToString();
 
    if (Request.Files["photos"] != null)
    {
        //The directory where photo will be saved.
        var directory = HttpContext.Server.MapPath("~/Photos");
        foreach (var photo in photos)
        {
            //Get the file name of photo as it being sent.
            //It's required to get the original file extension.
            var photoName = photo.FileName.ToString();
            var extension = Path.GetExtension(photoName).ToLower();
            //Give photo a new name so that it can avoid duplicate name.
            var newName = Guid.NewGuid() + extension;
            string filePath = Path.Combine(directory, newName);
 
            //Check file existence. If exist, try another name.
            if (System.IO.File.Exists(filePath))
            {
               newName = Guid.NewGuid() + extension;
            }
             
            string filePath = Path.Combine(directory, newName);
            photo.SaveAs(filePath); //saving the photo to directory.                    
        }
    }
 
    return RedirectToAction("Index", "UploadImage", new { auth = authString, issubmitted = true });
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s