簡體   English   中英

如何在Unity3D中使用PUT方法更新用戶圖片

[英]How to update user picture using PUT method in Unity3D

我是Unity3D的初學者; 我必須開發一個移動應用程序,並且需要管理用戶個人資料數據; 我必須使用REST服務與服務器通信這些數據。 當我從應用程序發送Json時,一切正常(例如姓名,電子郵件,電話號碼等),但我無法更新個人資料圖片。

我需要的是:Content-Type = multipart / form-data key =“ profile_picture”,value = 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)

在此處輸入圖片說明

任何幫助和代碼建議將不勝感激。 謝謝

使用Put ,通常只發送文件數據,而沒有表單。

您可以使用UnityWebRequest.Post添加多部分表單

IEnumerator Upload() 
{
    List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
    formData.Add(new MultipartFormFileSection("profile_picture", byte[], "example.png", "image/png"));

    UnityWebRequest www = UnityWebRequest.Post(url, formData);

    // change the method name
    www.method = "PUT"; 

    yield return www.SendWebRequest();

    if(www.error) 
    {
        Debug.Log(www.error);
    }
    else 
    {
        Debug.Log("Form upload complete!");
    }
}

使用MultipartFormFileSection


或者,您可以使用WWWForm

IEnumerator Upload()
{
    WWWForm form = new WWWForm();
    form.AddBinaryData("profile_picture", bytes, "filename.png", "image/png");

    // Upload via post request
    var www = UnityWebRequest.Post(screenShotURL, form);

    // change the method name
    www.method = "PUT";        

    yield return www.SendWebRequest();

    if (www.error) 
    {
        Debug.Log(www.error);
    }
    else 
    {
        Debug.Log("Finished Uploading Screenshot");
    }
}

使用WWWForm.AddBinaryData


請注意,對於用戶身份驗證,您必須正確編碼憑據:

string authenticate(string username, string password)
{
    string auth = username + ":" + password;
    auth = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(auth));
    auth = "Basic " + auth;
    return auth;
}

www.SetRequestHeader("AUTHORIZATION", authenticate("user", "password"));

來源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM