Sign In Register

How can we help you today?

Start a new topic
Answered

How to upload binary data with Unity?

I've just started using GameSparks and is trying to upload a texture. So far, I managed to retrieve the upload url with the following code

new GetUploadUrlRequest().Send((response) =>{
	StartCoroutine(UploadFile(response.Url));
});

 then in UploadFile, i used the url to send some binary data.

		// Create a Web Form
		var form = new WWWForm();
		form.AddField("somefield", "somedata");
		form.AddBinaryData("file", bytes, "hehe.png", "image/png");

		WWW w = new WWW(uploadURL, form);
		yield return w;

		if (w.error != null)
			Debug.Log(w.error);
		else
			Debug.Log(w.text);

i can see in my console the following result

GS: RECV:{"@class":".UploadCompleteMessage","messageId":"544f5afce4b078629d5d25d2","notification":true,"summary":".UploadCompleteMessage","playerId":"544f35d3e4b078629d5ccec0","uploadData":{"fileSize":2039,"playerId":"544f35d3e4b078629d5ccec0","uploadId":"3016b12579234a569797d93de9d637ff","origFileName":"hehe.png","fileName":"3016b12579234a569797d93de9d637ff-hehe.png"},"uploadId":"3016b12579234a569797d93de9d637ff"}


however, w.text only returns {"responseCode":0,"message":"Success"}.


I'm very sure this is not the correct way to upload stuff, and so someone could enlighten me.


Thanks a ton!


Best Answer

This is the correct way to upload a file, however you aren't getting the uploadId which would be required to get the file back from server. To do so you need to subscribe to the UploadCompleteMessage and get the uploadId from the UploadCompleteMessage that comes after a successful upload.


Here's a sample script that takes a screenshot, uploads it and can download it:

   

using UnityEngine;
using System.Collections;
using GameSparks.Api.Requests;

using GameSparks.Api.Messages;

public class UploadFile : MonoBehaviour {

	private string lastUploadId;
	public Texture2D downloadedImage;

	public void Start()
	{
		//We will be passing all our messages to a listener function
		UploadCompleteMessage.Listener += GetUploadMessage;
	}

	//Take a get our upload url
	public void UploadScreenShot () {
		new GetUploadUrlRequest().Send((response) =>
		{
			//Start coroutine and pass in the upload url
			StartCoroutine(UploadAFile(response.Url));	
		});
	}

	//Our coroutine takes the upload url
	public IEnumerator UploadAFile(string uploadUrl)
	{

		yield return new WaitForEndOfFrame();

		int width = Screen.width;
		int height = Screen.height;
		Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
		tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
		tex.Apply();
		//This basically takes a screenshot

		byte[] bytes = tex.EncodeToPNG(); //Can also encode to jpg, just make sure to change the file extensions down below
		Destroy(tex);

		// Create a Web Form
		var form = new WWWForm();
		form.AddField("somefield", "somedata");
		form.AddBinaryData("file", bytes, "hehe.png", "image/png");

		WWW w = new WWW(uploadUrl, form);
		yield return w;

		if (w.error != null)
		{
			Debug.Log(w.error);
		}
		else
		{
			Debug.Log(w.text);
		}
	}

	//This will be our message listener
	public void GetUploadMessage(GSMessage message)
	{
		//Every time we get a message
		Debug.Log(message.BaseData.GetString("uploadId"));
		//Save the last uploadId
		lastUploadId = message.BaseData.GetString("uploadId");
	}

	//When we want to download our uploaded image
	public void DownloadAFile()
	{
		//Get the url associated with the uploadId
		new GetUploadedRequest().SetUploadId(lastUploadId).Send((response) =>
			{
				//pass the url to our coroutine that will accept the data
				StartCoroutine(DownloadImage(response.Url));
			});
	}

	
	public IEnumerator DownloadImage(string downloadUrl)
	{
		var www = new WWW(downloadUrl);

		yield return www;

		downloadedImage = new Texture2D(200, 200);

		www.LoadImageIntoTexture(downloadedImage);
	}
}

   

You can save uploadIds to a leaderboard entry, challenge or user using scriptData.


Shane


Answer

This is the correct way to upload a file, however you aren't getting the uploadId which would be required to get the file back from server. To do so you need to subscribe to the UploadCompleteMessage and get the uploadId from the UploadCompleteMessage that comes after a successful upload.


Here's a sample script that takes a screenshot, uploads it and can download it:

   

using UnityEngine;
using System.Collections;
using GameSparks.Api.Requests;

using GameSparks.Api.Messages;

public class UploadFile : MonoBehaviour {

	private string lastUploadId;
	public Texture2D downloadedImage;

	public void Start()
	{
		//We will be passing all our messages to a listener function
		UploadCompleteMessage.Listener += GetUploadMessage;
	}

	//Take a get our upload url
	public void UploadScreenShot () {
		new GetUploadUrlRequest().Send((response) =>
		{
			//Start coroutine and pass in the upload url
			StartCoroutine(UploadAFile(response.Url));	
		});
	}

	//Our coroutine takes the upload url
	public IEnumerator UploadAFile(string uploadUrl)
	{

		yield return new WaitForEndOfFrame();

		int width = Screen.width;
		int height = Screen.height;
		Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
		tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
		tex.Apply();
		//This basically takes a screenshot

		byte[] bytes = tex.EncodeToPNG(); //Can also encode to jpg, just make sure to change the file extensions down below
		Destroy(tex);

		// Create a Web Form
		var form = new WWWForm();
		form.AddField("somefield", "somedata");
		form.AddBinaryData("file", bytes, "hehe.png", "image/png");

		WWW w = new WWW(uploadUrl, form);
		yield return w;

		if (w.error != null)
		{
			Debug.Log(w.error);
		}
		else
		{
			Debug.Log(w.text);
		}
	}

	//This will be our message listener
	public void GetUploadMessage(GSMessage message)
	{
		//Every time we get a message
		Debug.Log(message.BaseData.GetString("uploadId"));
		//Save the last uploadId
		lastUploadId = message.BaseData.GetString("uploadId");
	}

	//When we want to download our uploaded image
	public void DownloadAFile()
	{
		//Get the url associated with the uploadId
		new GetUploadedRequest().SetUploadId(lastUploadId).Send((response) =>
			{
				//pass the url to our coroutine that will accept the data
				StartCoroutine(DownloadImage(response.Url));
			});
	}

	
	public IEnumerator DownloadImage(string downloadUrl)
	{
		var www = new WWW(downloadUrl);

		yield return www;

		downloadedImage = new Texture2D(200, 200);

		www.LoadImageIntoTexture(downloadedImage);
	}
}

   

You can save uploadIds to a leaderboard entry, challenge or user using scriptData.


Shane

how can i modify this to upload multiple strings and be able to differentiate them upon download


 for upload i have this

var form = new WWWForm();
        form.AddField("somefield", "somedata");
        form.AddField("somefield", "somedata");
        form.AddField("somefield", "somedata");
       
 
        WWW w = new WWW(uploadUrl, form);
        yield return w;




 for download i seem to be stuck on how to request one or differentiate the three


 

var downloadform = new WWWForm();
        form.AddField("somefield", "somestring");
        form.AddField("somefield", "somestring");
        form.AddField("somefield", "somestring");
       
 
        WWW w = new WWW(downloadUrl, downloadform);
        yield return w;
        
        w.text

 

how can i modify this to upload multiple strings and be able to differentiate them upon download


 for upload i have this

1

2

3

4

5

6

7

8

var form = new WWWForm();

        form.AddField("somefield", "somedata");

        form.AddField("somefield", "somedata");

        form.AddField("somefield", "somedata");

        

  

        WWW w = new WWW(uploadUrl, form);

        yield return w;




 for download i seem to be stuck on how to request one or differentiate the three


 

1

2

3

4

5

6

7

8

9

10

var downloadform = new WWWForm();

        form.AddField("somefield", "somestring");

        form.AddField("somefield", "somestring");

        form.AddField("somefield", "somestring");

        

  

        WWW w = new WWW(downloadUrl, downloadform);

        yield return w;

         

        w.text

how can i modify this to upload multiple strings and be able to differentiate them upon download


 for upload i have this

1

2

3

4

5

6

7

8

var form = new WWWForm();

        form.AddField("somefield", "somedata");

        form.AddField("somefield", "somedata");

        form.AddField("somefield", "somedata");

        

  

        WWW w = new WWW(uploadUrl, form);

        yield return w;




 for download i seem to be stuck on how to request one or differentiate the three


 

1

2

3

4

5

6

7

8

9

10

var downloadform = new WWWForm();

        form.AddField("somefield", "somestring");

        form.AddField("somefield", "somestring");

        form.AddField("somefield", "somestring");

        

  

        WWW w = new WWW(downloadUrl, downloadform);

        yield return w;

         

        w.text

how can i modify this to upload multiple strings and be able to differentiate them upon download


 for upload i have this

 

var form = new WWWForm();
        form.AddField("somefield", "somedata");
        form.AddField("somefield", "somedata");
        form.AddField("somefield", "somedata");
        
  
        WWW w = new WWW(uploadUrl, form);
        yield return w;

 




 for download i seem to be stuck on how to request one or differentiate the three


 


 

var downloadform = new WWWForm();
        form.AddField("somefield", "somestring");
        form.AddField("somefield", "somestring");
        form.AddField("somefield", "somestring");
        
  
        WWW w = new WWW(downloadUrl, downloadform);
        yield return w;
         
        w.text

 

Alternatively im trying to upload .txt files over, i know how to convert them from binary back to txts but fail at converting the .txt files to binary files. Even after so im not quite sure on how to differentiate between the files upon download.


Examples would be great


Thnx


Cheers

Dear support team, I have been able to successfully upload a json file to the server using this method, now I would like to take that upload and save it to downloadables folder, how can I achieve that with cloud code? Thanks for your support

Login to post a comment