Using jquery ajax-upload with MVC3

UPDATE:
Check out this post for a nicer solution
END UPDATE

To get Ajax Upload to work with ASP.Net MVC3 is not immediately obvious as the way you save the file differs from the HttpPostedFile way.

My solution is based on this post on Stack Overflow.

The file I’m uploading also requires some parameters (companyId) in order to be saved correctly in my db too

The javascript looks like:

var uploader = new qq.FileUploader({
    // pass the dom node (ex. $(selector)[0] for jQuery users)
    element: document.getElementById('file-uploader'),
    // path to server-side upload script
    action: '/Companies/SaveCompanyFile?companyId=' + companyId,
    params: {
        companyId: companyId
    },
    onSubmit: function (id, fileName) {
        $('.qq-upload-list').hide();

        var fileDescription = $('#fileDescriptionSelectList').val()
        if(fileDescription == 'Other')
            fileDescription = $('#fileDescriptionOther').val();

        uploader.setParams({
            fileDescription: fileDescription
        });
    },
    onProgress: function (id, fileName, loaded, total) {
        $('.qq-upload-list').hide();
    },
    onComplete: function (id, fileName, responseJSON) {
        $('.qq-upload-list').hide();
        loadDocumentsList(companyId)
    },
    debug: true
});

Here is the controller action:

public JsonResult SaveCompanyFile(int companyId, string qqfile)
{
    byte[] fileData = null;

    using (var reader = new BinaryReader(Request.InputStream))
    {
        // This will contain the uploaded file data and the qqfile the name
        fileData = reader.ReadBytes((int)Request.InputStream.Length);
    }

    _service.SaveCompanyFile(companyId, qqfile, Request.ContentType, "Test", fileData);

    var data = new
    {
        success = true,
        hello = "yayu" + qqfile
    };

    return Json(data, JsonRequestBehavior.AllowGet);
}
Advertisements

16 thoughts on “Using jquery ajax-upload with MVC3

  1. hi i used above code:

    i am able to read stream ,image is saved.
    1. but when i click on saved image , image file appears to corrupted or damaged message is coming.

    2. what value will come in qqflie

    // UploadLogo( int companyId, string qqfile )

    //i am getting this value System.Web.HttpPostedFileWrapper ?????

    Mycode is :

    function UploadPhoto() {
    var companyId = 1;
    var uploader = new qq.FileUploader({
    element: document.getElementById(‘file-file_upload1’),
    action: ‘/Conference/UploadLogo?companyId=’ + companyId,

    onSubmit: function (id, fileName) {
    J$(‘.qq-upload-list’).hide();

    var fileDescription = J$(‘#fileDescriptionSelectList’).val()
    if (fileDescription == ‘Other’)
    fileDescription = J$(‘#fileDescriptionOther’).val();

    uploader.setParams({
    fileDescription: fileDescription
    });
    },
    onProgress: function (id,fileName, loaded, total) {
    J$(‘.qq-upload-list’).hide();
    },
    onComplete: function (id, fileName, responseJSON) {
    J$(‘.qq-upload-list’).hide();
    loadDocumentsList(companyId)
    },
    debug: true
    });
    }

    Controller function:

    public JsonResult UploadLogo(int companyId, string qqfile)
    {
    byte[] fileData = null;
    using (var reader = new BinaryReader(Request.InputStream))
    {
    fileData = reader.ReadBytes((int)Request.InputStream.Length);
    }

    var path = Server.MapPath(Const.themePath);
    var file = Path.Combine(path, “tt.jpg”);
    System.IO.File.WriteAllBytes(file, fileData);
    var data = new
    {
    success = true,
    hello = “yayu” + qqfile
    };

    return Json(data, JsonRequestBehavior.AllowGet);
    }

    }

  2. Not sure what’s happening exactly but it might be something to do with that technique not saving the ContentType properly.

    I tried over and over to try and extract or pass the ContentType to the server to no avail.

    So now, I use http://aquantum-demo.appspot.com/file-upload

    Here’s a sample of the Controller method I use


    public ActionResult SaveFile(int something, string description)
    {
    var vm = new SavedViewModel();
    byte[] fileData = null;

    if (Request.Files.Count == 0)
    vm.Message = "No files received.";
    else
    {
    HttpPostedFileBase uploadedfile = Request.Files[0];

    string filename = uploadedfile.FileName;
    string contentType = uploadedfile.ContentType;
    int fileSize = uploadedfile.ContentLength;

    using (var reader = new BinaryReader(uploadedfile.InputStream))
    fileData = reader.ReadBytes((int)uploadedfile.InputStream.Length);

    // SAVE HERE

    vm = new SavedViewModel { Message = "Saved", Info = new { Filename = filename, ContentType = contentType, FileSSize = fileSize } };
    }

    return Json(vm);
    }

    • I tried below syntax it worked:

      public JsonResult UploadLogo(int companyId, HttpPostedFileWrapper qqfile)
      {
      byte[] fileData = null;
      using (var reader = new BinaryReader(Request.InputStream))
      {
      fileData = reader.ReadBytes((int)Request.InputStream.Length);
      }

      var path = Server.MapPath(Const.themePath);
      var file = Path.Combine(path, “tt.jpg”);
      qqfile.SaveAs(file);

      var data = new {

      };

      return Json(data, JsonRequestBehavior.AllowGet);
      }

  3. Pingback: Using jQuery File Upload with ASP.NET MVC3 « Kiwidev

  4. How can we Validate for file extensions:

    I passed below value is it correct:

    allowedExtensions: ‘jpg, jpeg, png, gif’,

    In qq.FileUploaderBasic = function (o) {

    • see my response to to Henk below.

      Unfortunately i’m a bit snowed under but i’ll try and get something up when I can

      • sorry about that, some dooche kept complaining i didnt provide a complete solution (js + everything else) to his problem even though I stated clearly that it was only the controller code that was provided.

        I’ve since created a better post using a different solution that uses a different framework and that uses byte lookups on the serverside to determine the doctype.

        I’ll post that up when I have a bit more time.

  5. Can you tell me what new lib do you use?, because like a i said in my last comment, Im really new in MVC3 and JQuery so I dont have a clue how to start. By the way, thanks for you quickly answer

  6. I’ve had some success with implementing a C#/MVC3 solution based on ajaxupload (http://valums.com/ajax-upload/). First off, be aware that the javascript plugin uses two different methods to pass data to the server, depending on whether the visitor’s browser has proper support for XHR (later versions of Webkit/Mozilla) and falls back to an iframe-solution if not (basically IE).

    When implementing the solution in .NET, IE needs special treatment as the file data ends up in Request.Files[“qqfile”] as opposed to Request.InputStream. It also has another MIME-type, and requires you to return text/html status content instead of application/json, as the latter confuses IE and makes it try to download the server controller.

    I suspect this is due to IE using the iframe solution, but I haven’t had time to look further into it.

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