Created
September 16, 2013 11:23
-
-
Save Evgenus/6579434 to your computer and use it in GitHub Desktop.
Multi part upload with asynko
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static IEnumerable<IAsync> Upload(string version, string config, byte[] content, byte[] thumbnail = null) | |
{ | |
var multiPart = new MultiPartForm(); | |
multiPart.AddData("config", config); | |
multiPart.AddFile("content", "application/octet-stream", content); | |
if (thumbnail != null) | |
multiPart.AddFile("thumbnail", "image/png", thumbnail); | |
var url = MakeUrl("upload", version); | |
var request = CreatePOSTRequest(url).Call<HttpWebRequest>(); | |
yield return request; | |
request.Result.ContentType = multiPart.ContentType; | |
var requestStream = request.Result.GetRequestStreamAsync().Call<Stream>(); | |
yield return requestStream; | |
foreach (var part in multiPart.Parts) | |
{ | |
yield return requestStream.Result.WriteAllAsync(part).Call<int>(); | |
} | |
requestStream.Result.Close(); | |
var response = request.Result.GetResponseAsync().Call<HttpWebResponse>(); | |
yield return response; | |
if (response.Result.StatusCode != HttpStatusCode.OK) | |
throw new BadServerStatusException(response.Result.StatusCode); | |
var responseStream = response.Result.GetResponseStream(); | |
if (responseStream == null) | |
throw new NoResponseStreamException(response.Result); | |
var reading = responseStream.ReadBytesToEndAsync().Call<byte[]>(); | |
yield return reading; | |
var serverResponse = Serializer.Load<IServerResponse>(reading.Result); | |
var fail = serverResponse as Fail; | |
if (fail != null) | |
{ | |
Log("Fail {0}: {1}.", fail.FailType, fail.Message); | |
throw new FailResponseException(fail); | |
} | |
var success = serverResponse as Success; | |
if (success == null) | |
throw new UnexpectedResponseException(); | |
yield return Async.Result(serverResponse); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment