views:

40

answers:

1

I have a grails webservice that takes a binary file as a parameter. This is basically what it looks like:

def index = {
    switch(request.method){
    case "POST":
    def uploadedFile = request.getFile('file')
    File f=new File('c:/dev/newfile.tar');
    uploadedFile.transferTo(f);
    //do something with f
    break
    }
}

In order to test this, I was using curl - like so:

curl -F [email protected] http://localhost:8080/MyWebS/fileWS

The key being that in order for grails to know how to get the file, I had to define that file=thefile in the curl command.

How does this translate to getting C# to call this same webservice, and pass it a file. What would the file look like? a byte array?

+2  A: 

The simplest way is to use one of the WebClient.UploadFile overloads:

new WebClient().UploadFile("http://localhost:8080/MyWebS/fileWS",
                           "somefile.tar");

If you need more control than that offers, you can use HttpWebRequest.

Jeff Sternal
WebClient *does* multipart/form-data! Amazing. I wasn't aware of it.
dtb
Exactly what I was looking for! Thanks!
Derek
@Derek, glad to help! @dtb, I didn't realize it would be expecting an RFC2388 payload (er, actually, I didn't know what one was until I read your deleted post); some further reading suggests `WebClient.UploadFile` follows an earlier specification on which 2388 is based (RFC1867). It may well be compatible, but I'm just not 100% sure about the multipart/form-data business. ;) (Though surely the HttpWebRequest will do the trick if the UploadFile facade fails.)
Jeff Sternal
@Jeff Sternal: I used Reflector to look at WebClient.UploadFile. Which calls WebClient.OpenFileInternal which, in turn, constructs a wonderful *multipart/form-data* payload that even uses "file" for the name of the form field. So it's exactly what the OP was looking for.
dtb
I found a good document concerning the other restful methods here: http://developer.yahoo.com/dotnet/howto-rest_cs.html
Derek
@Derek: That doesn't look like a good resource. [WebClient.UploadValues](http://msdn.microsoft.com/en-us/library/9w7b4fz7.aspx) is *much* better than what the example code for "Simple POST Requests" does. The other examples look aweful to me as well. Don't use HttpWebRequest when you can use [WebClient](http://msdn.microsoft.com/en-us/library/tt0f69eh.aspx). (There are cases in which WebClient cannot be used, but WebClient constantly amazes me what it *can* do!)
dtb
What i meant was, it seemed like a good resource if you werent going to use WebClient..or no? I am not a C# developer at all, just needed to create a quick tester for my webservice
Derek