0

Have an MVC application and a separate WebAPI. Using plupload, when the url points to a method in the MVC controller, the files are POSTed.

Here's what Fiddler shows

POST /Home/HandleUpload/ HTTP/1.1
Host: localhost:50000
Connection: keep-alive
Content-Length: 38040
Origin: http://localhost:50000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryT4glpqFi5sbmY2KL
Accept: */*
Referer: http://localhost:50000/Home/Index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

When I change the url to point to the WebAPI, I get OPTIONS request instead of a POST, so the API method doesn't get hit.

OPTIONS /api/v1/Files/HandleUpload HTTP/1.1
Host: localhost:60000
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:50000
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:50000/Home/Index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

The only thing I change on the plupload configuration is the url.

Here's my method. It's the same in both projects.

[HttpPost]
public HttpResponseMessage HandleUpload(int? chunk, string name)
{
    var fileUpload = HttpContext.Current.Request.Files[0];
    var uploadPath = HttpContext.Current.Server.MapPath("~/App_Data");
    chunk = chunk ?? 0;

    //write chunk to disk.   
    string uploadedFilePath = Path.Combine(uploadPath, name);
    using (var fs = new FileStream(uploadedFilePath, chunk == 0 ? FileMode.Create : FileMode.Append))
    {
        var buffer = new byte[fileUpload.InputStream.Length];
        fileUpload.InputStream.Read(buffer, 0, buffer.Length);
        fs.Write(buffer, 0, buffer.Length);
    }
}
5
  • 3
    you seem to be doing a cross domain request. check this tutorial for more info: asp.net/web-api/overview/security/…
    – Kiran
    Oct 31, 2013 at 16:54
  • I can change [HttpPost] to [HttpOptions] on the API and I'll hit the method. In this case the Request.Files[0] is null so an exception is thrown. I would expect the request from MVC to be a POST not OPTIONS.
    – gene
    Oct 31, 2013 at 17:40
  • My form enctype is multipart/form-data. Could this issue be that my form action is a different origin than my plupload url?
    – gene
    Oct 31, 2013 at 18:26
  • As @KiranChalla already pointed out, the OPTIONS request is the CORS preflight request and thats why Request.Files[0] is null. You have to decorate your controller with the EnableCorsAttribute. Nov 2, 2013 at 18:42
  • Thanks. That got it working. I wasn't expecting the request type to change.
    – gene
    Nov 5, 2013 at 16:11

1 Answer 1

1

I was able to do this but not sure if this is the best practice. filename is set in UI in the preinit function

preinit: {
                            UploadFile: function (up, file) {


                                // You can override settings before the file is uploaded
                                // up.settings.url = 'upload.php?id=' + file.id;
                                //up.settings.multipart_params = { type: $("#Type").val(), title: $("#Title").val() };
                                up.settings.multipart_params = {
                                    filename: file.name
                                };

                            }
                        },

Web api code

[HttpPost]
            public async Task<IHttpActionResult> UploadPropertyImage()
            {
                if (!Request.Content.IsMimeMultipartContent())
                    throw new Exception(); // divided by zero

                var provider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);



                var name = await provider.Contents.SingleOrDefault(p => p.Headers.ContentDisposition.Name == "\"name\"").ReadAsStringAsync();
                var chunk = await provider.Contents.SingleOrDefault(p => p.Headers.ContentDisposition.Name == "\"chunk\"").ReadAsStringAsync();
                var chunks = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"chunks\"").ReadAsStringAsync();
                var filename = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"filename\"").ReadAsStringAsync();
                var buffer = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"file\"").ReadAsByteArrayAsync();
                //var Id = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"Id\"").ReadAsByteArrayAsync();
                var Id = Guid.Empty;

                var uploadPath =  HostingEnvironment.MapPath(Path.Combine("~/app_data",Id.ToString()));


                if (!Directory.Exists(uploadPath))
                    Directory.CreateDirectory(uploadPath);

                using (var fs = new FileStream(Path.Combine(uploadPath,name), chunk == "0" ? FileMode.Create : FileMode.Append))
                      fs.Write(buffer, 0, buffer.Length);


                return Ok();
            }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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