亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

帶有改裝的多部分內容

帶有改裝的多部分內容

C#
喵喔喔 2021-11-21 10:18:32
我正在將 multipart 與 Refit 一起使用。我嘗試為我的服務上傳個人資料圖片,郵遞員生成的代碼看起來像這樣var client = new RestClient("http://api.example.com/api/users/1");var request = new RestRequest(Method.POST);request.AddHeader("Postman-Token", "xxx");request.AddHeader("Cache-Control", "no-cache");request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"_method\"\r\n\r\nput\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"profile_picture\"; filename=\"ic_default_avatar.png\"\r\nContent-Type: image/png\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);IRestResponse response = client.Execute(request);然后我像這樣構造 Refit 方法[Multipart][Post("/users/{id}")]IObservable<BaseResponse<User>> UpdateProfilePicture(int id,[AliasAs("profile_picture")] byte[] profilePicture,[AliasAs("_method")]string method="put");如果我使用byte[]否則ByteArrayPart它會拋出異常{System.Net.Http.HttpRequestException:發送請求時出錯---> System.Net.WebException:獲取響應流時出錯(分塊Read2):ReceiveFailure ---> System.Exception:在System.Net.WebConnection .HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x00031] in :0 at System.Net.WebConnection.Read (System.Net.HttpWebRequest request, System.Byte[] buffer, System .Int32 offset, System.Int32 size) [0x000d2] in :0 at System.Net.WebConnectionStream.ReadAll () [0x0010e] in :0 at System.Net.HttpWebResponse.ReadAll () [0x00011] in :0 at System.. 如果我使用StreamorStreamPart它也會拋出異常表示流已關閉。
查看完整描述

2 回答

?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

您可以使用IEnumerable<StreamPart>上傳文件:

  [Multipart]
  [Post("/users/{id}")]  
  Task UpdateProfilePicture(int id, [AliasAs("profile_picture")] IEnumerable<StreamPart> streams);



查看完整回答
反對 回復 2021-11-21
?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

這是一個老問題,但也許它可以幫助其他人。


我也無法使用StreamPart,因為在服務器端收到的文件大小始終為 0,所以我ByteArrayPart改為使用github.com/reactiveui/refit#multipart-uploads 中指定的那樣。


界面:


[Multipart]

[Post("/api/<some-path>")]

Task<HttpResponseMessage> Upload([AliasAs("file")] ByteArrayPart bytes);

用法:


var stream;

using (MemoryStream ms = new MemoryStream())

{

    stream.CopyTo(ms);

    client.Upload(new ByteArrayPart(ms.ToArray(), fileName));

}

請注意,此技術將在內存中加載整個流! 它對我有用,因為我有小文件,但是如果您正在處理大文件或內存使用問題,您應該找到更好的方法。


查看完整回答
反對 回復 2021-11-21
  • 2 回答
  • 0 關注
  • 261 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號