Ariel
Ariel

Reputation: 5830

Upload file async issue with jQuery forms to a WCF service

I need to wrap this up but not sure how :-)

Basically, I'm using jQuery forms to upload a file to a WCF REST service.

Client looks like:

<script type="text/javascript">
    $(function () {
        $('form').ajaxForm(
            {
                url: '/_vti_bin/VideoUploadService/VideoUploadService.svc/Upload/theFileName',
                type: 'post'
            })
    });
</script>
<form id="fileUploadForm" name="fileUploadForm" method="post" action="/_vti_bin/VideoUploadService/VideoUploadService.svc/Upload" enctype="multipart/form-data">
  <input type="text" name="filename" />
  <input type="file" id="postedFile" name="postedFile" />
  <input type="submit" id="fileUploadSubmit" value="Do Upload" />
</form>

While server relevant snippets are

[WebInvoke(UriTemplate = "Upload/{fileName}", ResponseFormat = WebMessageFormat.Json)]
void Upload(string fileName, Stream fileStream);

public void Upload(string fileName, Stream stream)
{
   // just write stream to disk...
}

Problem is that what I write to disk looks like this, not the content of the file (in my case, "0123456789"):

-----------------------------7dc7e131201ea
Content-Disposition: form-data; name="MSOWebPartPage_PostbackSource"

// bunch of same stuff here

-----------------------------7dc7e131201ea
Content-Disposition: form-data; name="filename"

fdfd
-----------------------------7dc7e131201ea
Content-Disposition: form-data; name="postedFile"; filename="C:\Inter\Garbage\dummy.txt"
Content-Type: text/plain

0123456789
-----------------------------7dc7e131201ea--

Question - should I be manually parsing what I get above and extract the last part which corresponds to the uploaded file (not elegant)? Or there is a way to apply attribute, content type, whatever setting, in order to get in the stream JUST the uploaded file's content?

I'm suspect there is, but I'm missing it... any help?

Thanks much!

Upvotes: 1

Views: 910

Answers (1)

Regfor
Regfor

Reputation: 8101

Take a look at 2 articles about Form file upload using ASP.NET Web API:

http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1

http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2

ASP.NET Web API already has classes (like MultipartFormDataStreamProvider) to parse multipart requests and also to save data from them. Why not to use these classes to solve your problem

UPD In case of .NET 3.5 code and hosting:

Think that MultipartFormDataStreamProvider class and it's assembly aren't for .NET 3.5. In these case you should use some other library/class to parse multipart or do it manually.

Try following project (MIT license) and file HttpMultipartParser.cs from this project:

https://bitbucket.org/lorenzopolidori/http-form-parser/src

Upvotes: 1

Related Questions