pablomargolin
pablomargolin

Reputation: 59

How to write HTTP post sending an image file (.jpg/.png) in Unity by using UnityWebRequest?

I want to do a post request in Unity using UnityWebRequest. I have to send a jpg image or png image and the api has to response with a string message or int code.

How to write the C# Script to send the data through post?

Upvotes: 2

Views: 2080

Answers (1)

Neighborhood Ghost
Neighborhood Ghost

Reputation: 844

Check this out I'm using this method for a long time and it's working for me.

public static IEnumerator CallAPIwithPostAndFileData1(string api_url, List<FileDetails> files, Action<string> callback)
{
    WWWForm form = new WWWForm();
    int i = 0;
    foreach (FileDetails file in files)
    {
        i++;
        UnityWebRequest localFile = UnityWebRequest.Get(@"file://" + file.filePath);
        yield return localFile;
        form.AddBinaryData("image[]", localFile.downloadHandler.data, file.fileName, "image/" + file.fileType);
    }

    UnityWebRequest request = UnityWebRequest.Post(api_url, form);
    request.SetRequestHeader("Content-Type", "application/json");
    request = APIHelper.setAuthToRequest(request, AuthType.BASIC);
    request.SendWebRequest();

    while (!request.isDone)
    {
        downloadProgress = request.downloadProgress * 100;
        yield return null;
    }

    if (request.isDone && (!request.isHttpError || !request.isNetworkError))
    {
        callback(request.downloadHandler.text);
    }
    else if (request.isHttpError || request.isNetworkError)
    {
        Debug.LogError(request.error);
    }
}

FileDetails This class is only holding some necessary values for me like filepath, fileName, and filetype. It's a bit too long let me know if you don't understand anything.

Upvotes: 2

Related Questions