Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 Web Api ajax file upload

I am developing some sort of service using asp.net mvc 4 web api. On one form user must upload few files and then submit form to server. Problem is in ajax file upload to asp.net mvc web api. I have already implemented upload without ajax. But i need it's done with ajax. This is implementation of

public Task<HttpResponseMessage> PostJob()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
    }

    string path = HttpContext.Current.Server.MapPath(string.Format("~/Resources/Documents"));
    MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(path);
    var request = Request.Content.ReadAsMultipartAsync(provider);

    var task = request.ContinueWith<HttpResponseMessage>(t =>
    {
        if (t.IsFaulted || t.IsCanceled)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }

        string fileName = provider.BodyPartFileNames.FirstOrDefault().Value;
        string originalName = provider.BodyPartFileNames.FirstOrDefault().Key.TrimStart('"').TrimEnd('"');
        string RandomName = provider.BodyPartFileNames.First().Value + Path.GetExtension(originalName);

        FileInfo file = new FileInfo(fileName);
        file.CopyTo(Path.Combine(path, originalName), true);
        file.Delete();


        return new HttpResponseMessage(HttpStatusCode.Created);

    });

I have found article that does this using HTML5 http://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net-webapi/. I need this work in IE8. Maybe you have any ideas?

Any help is appreciated, Iryna.

like image 515
Iryna Avatar asked Jul 28 '12 17:07

Iryna


1 Answers

You cannot upload files using pure javascript with AJAX in legacy browsers such as IE8. The reason for this is that you don't have access to the file contents that was selected by the user in a file input. And since you don't have access to this contents, you cannot send it to the server.

You could use some of the existing file upload plugins:

  • Plupload
  • Blueimp
  • Valums Ajax Upload
  • Uploadify

They will test the capabilities of the browser and if it supports HTML5 and the new XHR2 object which allows uuploading files with AJAX it will use that. Or if the browser doesn't support it, the plugin could fallback to either Flash or hidden iframes. So if you need to support legacy browsers you don't have much choice but either use some other client scripting technology such as Flash or use a hidden iframe which fakes the AJAX request and actually sends a normal multipart/form-data request.

like image 138
Darin Dimitrov Avatar answered Oct 02 '22 15:10

Darin Dimitrov