Windows Phoneの写真のアップロードをリセットします
-
14-11-2019 - |
質問
私はRestSharpを使ってWindows Phone 7アプリケーションで写真をREST APIにアップロードしようとしています。
POSTパラメータは次のとおりです。
写真: マルチパート/フォームデータとしてエンコードされた写真
photo_album_id : イベントやグループである可能性がある既存のフォトアルバムの識別子 アルバム私は私の要求を作成しました、しかし私が
"{\"details\":\"missing photo parameter\",\"problem\":\"The API request is malformed\"}\n
を取り戻すたびにマイ写真パラメータは次のようになります:
"-------------------------------------- 8 CD9BFAFB3CA00 \ R \ NContent-disposition:form-data; name= \" filename \ " ; filename="somefile.jpg \" \ r \ ncontent型:image / jpg \ r \n\ r \ n(ここにリストされているいくつかのバイナリ迷惑)\ r \n------------ -------------------- 8CD9BFAFB3CA00 - "
私がイメージのバイナリデータを提示しているのかという問題であるかどうかは問題ありません(現在私のPhotoTaskCompletedイベントにあるイベントには、E.cchosenphotoの内容をバイト[]に読み、それを渡します。フォームデータを作成するためのヘルパーメソッドまたは私がフォームを正しく作成しない場合は
私はできるだけ簡単にこれをやろうとしているだけで、私はそれがすべてうまくいくのか知っていたらリファクタリングすることができます。
.void ImageObtained(object sender, PhotoResult e) { var photo = ReadToEnd(e.ChosenPhoto); var form = PostForm(photo); var request = new RequestWrapper("photo", Method.POST); request.AddParameter("photo_album_id", _album.album_id); request.AddParameter("photo", form); request.Client.ExecuteAsync<object>(request, (response) => { var s = response.Data; }); } private string CreateBoundary() { return "---------------------------" + DateTime.Now.Ticks.ToString("x"); } private string PostForm(byte[] data) { string boundary = CreateBoundary(); StringBuilder post = new StringBuilder(); post.Append(boundary); post.Append("\r\n"); post.Append("Content-Disposition: form-data; name=\"filename\"; filename=\"somefile.jpg\""); post.Append("\r\n"); post.Append("Content-Type: image/jpg"); post.Append("\r\n\r\n"); post.Append(ConvertBytesToString(data)); post.Append("\r\n"); post.Append("--"); post.Append(boundary); post.Append("--"); return post.ToString(); } public static string ConvertBytesToString(byte[] bytes) { string output = String.Empty; MemoryStream stream = new MemoryStream(bytes); stream.Position = 0; using (StreamReader reader = new StreamReader(stream)) { output = reader.ReadToEnd(); } return output; }
解決
Hammock for Windows Phone makes this real simple.
You just add the file to the request using the AddFile
method and pass it the photo stream.
var request = new RestRequest("photo", WebMethod.Post);
request.AddParameter("photo_album_id", _album.album_id);
request.AddFile("photo", filename, e.ChosenPhoto);
他のヒント
Hum are you sure that your PostForm is correct ? The content-* params should be set in the headers of your POST and not in the body ?
var request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add(HttpRequestHeader.Authorization,"blabla");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";