Reputation:
I want to be able to post a file and as part of that post add data.
Here is what I have:
var restRequest = new RestRequest(Method.POST);
restRequest.Resource = "some-resource";
restRequest.RequestFormat = DataFormat.Json;
string request = JsonConvert.SerializeObject(model);
restRequest.AddParameter("text/json", request, ParameterType.RequestBody);
var fileModel = model as IHaveFileUrl;
var bytes = File.ReadAllBytes(fileModel.LocalStoreUrl);
restRequest.AddFile("FileData", bytes, "file.zip", "application/zip");
var async = RestClient.ExecuteAsync(restRequest, response =>
{
if (PostComplete != null)
PostComplete.Invoke(
new Object(),
new GotResponseEventArgs
<T>(response));
});
It posts the file fine but the data is not present - is this even possible?
[UPDATE]
I have amended the code to use the multi-part header:
var restRequest = new RestRequest(Method.POST);
Type t = GetType();
Type g = t.GetGenericArguments()[0];
restRequest.Resource = string.Format("/{0}", g.Name);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddHeader("content-type", "multipart/form-data");
string request = JsonConvert.SerializeObject(model);
restRequest.AddParameter("text/json", request, ParameterType.RequestBody);
var fileModel = model as IHaveFileUrl;
var bytes = File.ReadAllBytes(fileModel.LocalStoreUrl);
restRequest.AddFile("FileData", bytes, "file.zip", "application/zip");
var async = RestClient.ExecuteAsync(restRequest, response =>
{
if (PostComplete != null)
PostComplete.Invoke(
new Object(),
new GotResponseEventArgs
<T>(response));
});
Still no luck... any pointers?
Upvotes: 10
Views: 4493
Reputation: 2143
I am not sure if this is going to help. But give it a try.
Since you are attempting to pass it as text/json you may try to convert your byte array to a string and add it to the request.
To convert it to a string you may do something like this.
public string ContentsInText
{
get
{
return Encoding.Default.GetString(_bytecontents);
}
}
To convert it to a byte array you may do this. Most probably you will have to do this in your web service.
public byte[] ContentsInBytes
{
get { return Encoding.Default.GetBytes(_textcontents); }
}
Upvotes: 1
Reputation: 50245
I am not an expert in C#
but I used the same principle in Grails/Java for multipart requests.
Some pointers (ServiceStack/C#)
Multipart Form Post
MSDN MIME Message
ServiceStack File Attachment
Java corresponds:
Posting File and Data as JSON in REST Service
I hope this helps.
Upvotes: 3