0

My web application interacts with the server-side (ASP.NET MVC 3) by posting JSON data to certain URLs (without using html forms).

How can I post file to the server and bind it to HttpPostedFileBase using JSON and without using multipart forms?

Thanks!

Dmitrii
  • 1,247
  • 4
  • 14
  • 28

2 Answers2

2

I have done this but did not use the HttpPostedFileBase to get the content from the MVC app. I simply used JSON.

You can simply use the FileReader.onload (on HTML5) method to extract the file content and post as a Base64 string directly to the MVC controller. The #upload-button is an <input type=file ...> tag.

    var file = $('#upload-button')[0].files[0];
    var reader = new FileReader();
    reader.onload = (function (f) {
        return function (e) {
            if (e.target.readyState == FileReader.DONE) {
                $.ajax("FileStore/SavePicture", {
                    data: { content: e.target.result, name: f.name },
                    type: "post",
                    contentType: "application/json"
                });
            }
        };
    })(file)

From there you can use Convert.FromBase64String method to conver to a byte[]. This is how the Action content look like;

    string base64String = content;
    // Get the starting point of the actual content from the base64String.
    int start = base64String.IndexOf(",") + 1;
    int length = base64String.Length - start;
    contentAsString = base64String.Substring(start, length);

    byte[] dataAsBytes = Convert.FromBase64String(contentAsString);

There might be some other ways of doing this.

  • Yes, I did that but there is another problem. In fact, I'm using JavaScriptSerializer to deserialize the JSON and base64 string is not deserialized automatically to HttpPostedFileBase property.Perhaps, there is any attribute which could be applied to the HttpPostedFileBase property of the model so that I could customize deserialization process for this certain property? – Dmitrii Sep 19 '12 at 12:20
  • Yes, didn't work for me either. So I used this approach instead as a work-around solution. – It's actually me Sep 19 '12 at 12:27
0

It could be done, but you will have cross-browser problems, more details you can find here: How can I upload files asynchronously with jQuery? OR just google "ajax file upload"

Community
  • 1
  • 1
webdeveloper
  • 17,174
  • 3
  • 48
  • 47