J'hack le lezard
J'hack le lezard

Reputation: 413

Send POST request with Image from Unity3D

I'm trying to send an image to my NodeJS API from Unity but unfortunately I can't make it work. Here is an extract of my c# code:

private string POSTUrl = "http://myNodeJSAPI.com/upload-image";
private Dictionary<string, string> postHeader = new Dictionary<string, string>();

public WWW POST() {
    WWW www;
    postHeader["content-Type"] = "application/octet-stream";
    postData = File.ReadAllBytes("Assets/Resources/ImageIWantToSend.png");
    www = new WWW(POSTUrl, postData, postHeader);
    StartCoroutine(WaitForRequest(www));
    return www;
}

IEnumerator WaitForRequest(WWW www)
{
    yield return www;
    if (www.error == null)
    {
        Debug.Log("WWW Ok!: " + www.text);
    }
    else
    {
        Debug.Log("WWW Error: " + www.error);
    }
}

and here the relevant part of my nodejs one:

app.post('/upload-image', rawBody, function (req, res) {
        console.log("File received!");
        if (req.rawBody && req.bodyLength > 0) {
            fs.writeFile("/tmp/ImageIWantToSend.png", req.rawBody, function (err) {
                if (err) {
                    return console.log(err);
                }
                console.log("Image has been saved! Starting other things...");
            })
        }
    }

The request is sent but never received by the API (I get 503 bad gateway). I try the same request outside Unity and it seems to work (using Postman: basic post request with image attached as binary).

Did I make a mistake, or is there another way to achieve this? Thanks!

EDIT: I finally solved the problem by changing application/octet-stream to text/html. If there is a better way to send data to Nodejs I'm still interested

Upvotes: 0

Views: 3650

Answers (1)

Vladyslav Melnychenko
Vladyslav Melnychenko

Reputation: 940

Check out Unity's new UnityWebRequest class.It is a replacement for original WWW.

You can also use C# WebClient or HttpWebRequest class. They work with Unity if you are not using WebGL build.

This is also a good unity plugin to handle requests, though it is not free.

Upvotes: 1

Related Questions