猿问

如何在 Unity3D 中使用 PUT 方法更新用户图片

我是Unity3D的初学者;我必须开发一个移动应用程序,我需要管理用户个人资料数据;我必须使用REST服务与服务器通信这些数据。当我从我的应用程序发送Json(例如姓名,电子邮件,电话号码等)时,一切正常,但我无法更新个人资料图片。

我需要的是:内容类型=多部分/表单数据键=“profile_picture”,值=file_to_upload(不是路径)

我阅读了很多关于Unity中的网络的信息,并尝试了UnityWebRequest,List,WWWform的不同组合,但似乎没有什么适用于这种PUT服务。

UnityWebRequest www = new UnityWebRequest(URL + user.email, "PUT");
    www.SetRequestHeader("Content-Type", "multipart/form-data");
    www.SetRequestHeader("AUTHORIZATION", authorization);    //i think here i'm missing the correct way to set up the content

我可以正确地模拟Postman的更新,所以这不是服务器的问题;我很确定问题是我无法在应用程序内转换此逻辑。

从邮递员上传正确工作(1)

从邮递员上传正确工作(2)

http://img4.mukewang.com/6300a5130001a61b15270960.jpg

任何类型的帮助和代码建议将不胜感激。谢谢


海绵宝宝撒
浏览 140回答 1
1回答

拉莫斯之舞

使用 Put,您通常只发送文件数据,而不发送表单。您可以使用 UnityWebRequest.Post 添加多部分表单IEnumerator Upload()&nbsp;{&nbsp; &nbsp; List<IMultipartFormSection> formData = new List<IMultipartFormSection>();&nbsp; &nbsp; formData.Add(new MultipartFormFileSection("profile_picture", byte[], "example.png", "image/png"));&nbsp; &nbsp; UnityWebRequest www = UnityWebRequest.Post(url, formData);&nbsp; &nbsp; // change the method name&nbsp; &nbsp; www.method = "PUT";&nbsp;&nbsp; &nbsp; yield return www.SendWebRequest();&nbsp; &nbsp; if(www.error)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Debug.Log(www.error);&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Debug.Log("Form upload complete!");&nbsp; &nbsp; }}使用多部分表单文件部分或者,您可以使用 WWWFormIEnumerator Upload(){&nbsp; &nbsp; WWWForm form = new WWWForm();&nbsp; &nbsp; form.AddBinaryData("profile_picture", bytes, "filename.png", "image/png");&nbsp; &nbsp; // Upload via post request&nbsp; &nbsp; var www = UnityWebRequest.Post(screenShotURL, form);&nbsp; &nbsp; // change the method name&nbsp; &nbsp; www.method = "PUT";&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; yield return www.SendWebRequest();&nbsp; &nbsp; if (www.error)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Debug.Log(www.error);&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Debug.Log("Finished Uploading Screenshot");&nbsp; &nbsp; }}使用 WWWForm.AddBinaryData请注意,对于用户身份验证,您必须正确编码凭据:string authenticate(string username, string password){&nbsp; &nbsp; string auth = username + ":" + password;&nbsp; &nbsp; auth = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(auth));&nbsp; &nbsp; auth = "Basic " + auth;&nbsp; &nbsp; return auth;}www.SetRequestHeader("AUTHORIZATION", authenticate("user", "password"));
随时随地看视频慕课网APP
我要回答