Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using an ajax form for sending the multiple files upload to the server. This is what my form looks like

   @using (@Ajax.BeginForm("SaveProjectSummary", "Project", new { id = Model.ProjectId }, new AjaxOptions { OnSuccess = "Add_OnCompleteSummarySave()" }, new { enctype = "multipart/form-data" }))

I can that leads me to my desired action but I can't find anything inside Request.Files on server. just want to be sure if I'm using this the right which doesn't seem to me so any help will be much appreciated.

share|improve this question

4 Answers

Sadly, Ajax.BeginForm cannot be used to upload files.

  • There are plugins like uploadify

http://www.uploadify.com/forum/#/discussion/1685/uploadify-and-ajax/p1

  • or this jquery plugin

http://malsup.com/jquery/form/

share|improve this answer
that's scary.. trying with normal form... – afr0 Feb 21 at 4:55
1  
@afr0, normal Html.BeginForm would do it. But there are AJAX approaches. Check my revised answer for some alternatives. – Dave A Feb 21 at 4:57
i dont want to include swf. – afr0 Feb 21 at 7:20

Another great uploader component is PlUpload

http://www.plupload.com/

It does:

  • chucked file uploader, so you can upload large files. E.g. 100Mb
  • file scaling on client side
  • drag and drop file selection

FYI, server-side code in .NET to handle post requests from PlUpload:

var chunk = Request.Form["chunk"] != null ? int.Parse(Request.Form["chunk"]) : 0;

var fileName = Request.Form["name"] ?? "";

//open a file, if our chunk is 1 or more, we should be appending to an existing file, otherwise create a new file
var fs = new FileStream(Server.MapPath("/files/" + fileName), chunk == 0 ? FileMode.OpenOrCreate : FileMode.Append);

//write our input stream to a buffer
var buffer = new Byte[Request.Files[0].InputStream.Length];
Request.Files[0].InputStream.Read(buffer, 0, buffer.Length);

//write the buffer to a file.
fs.Write(buffer, 0, buffer.Length);
fs.Close();

If you're keen to roll your own component, check File System API available on modern browsers. It allows you to get file content binary and upload it using AJAX call

share|improve this answer
very interesting. want to test drive this one. – Dave A Feb 21 at 5:11
1  
I've used it for image uploading for geolocation.ws Have a look how it works – Maksym Kozlenko Feb 21 at 5:16
1  
@MaksymKozlenko does it work with asp.net mvc ajax form helper? – afr0 Feb 21 at 7:20
@afr0: No. PlUpload client side code makes AJAX request with image data. – Maksym Kozlenko Feb 21 at 21:03

[HttpPost] public JsonResult UploadImage(HttpPostedFileWrapper imageFile) {

        if (imageFile == null || imageFile.ContentLength == 0 || imageFile.ContentLength > 205168)
        {

            return new JsonResult
            {
                ContentType = "text/html",
                Data = "No file was uploaded."

            };
        }

        if (imageFile == null || imageFile.ContentLength == 0 || (imageFile.ContentType != "image/png" && imageFile.ContentType != "image/jpg" && imageFile.ContentType != "image/jpeg" && imageFile.ContentType != "image/pjpeg"))
        {
            return new JsonResult
            {
                ContentType = "text/html",
                Data = "Type"
            };
        }
        if (Session["CityId"] != null)
        {
            if (MdlNadal == null)
            {
                MdlNadal = new mdlNadal();
            }
            string strFilePaths = "";

            int CityId = Convert.ToInt32(Session["CityId"].ToString());
            string strCityName = "";
            if (Session["CityName"] != null)
            {
                strCityName = Session["CityName"].ToString();
            }

            string strFileNames = imageFile.FileName.Replace(@"\", "/");
            string imgPath = ConfigurationManager.AppSettings["ImagePath"].ToString().Replace("~", "");
            strFileNames = strFileNames.Split('/')[strFileNames.Split('/').Length - 1];
            Session["ImageName"] = strFileNames;
            ViewBag.ImageName = strFileNames;
            strFilePaths = Request.Url.Scheme + "://" + Request.Url.Authority + imgPath + strCityName + "" + CityId + "/" + strFileNames;
            MdlNadal.UpdateCityImageByCityID(CityId, strFilePaths);
            if (imageFile != null)
            {
                if (!Directory.Exists(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["ImagePath"].ToString() + strCityName + "" + CityId))))
                {
                    Directory.CreateDirectory(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["ImagePath"].ToString() + strCityName + "" + CityId)));
                }
                else
                {
                    int counts = Directory.GetFiles(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["ImagePath"].ToString() + strCityName + "" + CityId))).Count();
                    if (counts > 1)
                    {
                        string[] StrArr = Directory.GetFiles(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["ImagePath"].ToString() + strCityName + "" + CityId)));
                        for (int i = 0; i <= counts - 1; i++)
                        {
                            string strFileNameCheck = StrArr[i];
                            //strFileNameCheck = strFileNameCheck.Replace(@"\", "/");
                            //strFileNameCheck = strFileNameCheck.Split('/')[strFileNameCheck.Split('/').Length - 1];
                            try
                            {
                                System.IO.File.Delete(strFileNameCheck);
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }

                        }
                    }
                }
                var FilePath = Path.Combine(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["ImagePath"].ToString() + strCityName + "" + CityId)), strFileNames);
                imageFile.SaveAs(FilePath);
            }

        }

        return new JsonResult
        {
            ContentType = "text/html",
            Data = "Save"

        };
    }

@using (Html.BeginForm("UploadImage", "Nadal", FormMethod.Post, new { enctype = "multipart/form-data", id = "mws-Validate", target = "UploadTarget", @class = "mws-form" })) {

                    <label class="title10">
                        <strong>Choose a background for this city</strong>
                    </label>                                             
                    <div class="mws-form-item large">
                        <input type="file" name="imageFile" id="imageFile" onchange="return SetAttachFlag();" />
                        (Supported File Types : .jpg, .jpeg, .png) (Maximum Size: 200 Kb)
                        <iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute;
                            left: -999em; top: -999em;"></iframe>
                    </div>

                }
share|improve this answer
I don't want use BeginForm thats the only problem with your code – afr0 Feb 22 at 14:54
btw you don't have to use iframe to post image from BeginForm. – afr0 Feb 22 at 14:58

Why not take advantage of the File API in HTML5. Have a look at these links to point you in the right direction.

http://www.html5rocks.com/en/tutorials/file/dndfiles/

http://timothypoon.com/blog/2011/05/10/ajax-uploading-with-html5s-file-api/

share|improve this answer
I really like the HTML5 File Apis and gave it a try and it works with chrome and FF but IE9 that I'm using doesn't support these APIs thats really sucks from MS they are going in the open source direction with this kind of browser ..only some genius can come up with this idea – afr0 Feb 22 at 7:21
i did achieve the multiple files sending to the server with Html.BeginForm but it requires the whole form to be submitted along with files which kind of breaks all of my user experience so i think now jquery is my last bet – afr0 Feb 22 at 7:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.