Sign In Register

How can we help you today?

Start a new topic

Uploading and retrieving an image from Unity to GameSparks

Here's a sample script that takes a screenshot, uploads it to GameSparks and then allows you to re-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;
    //This will get our upload url and on the response we will start our coroutine to take the screenshot
    public void UploadScreenShot () {
        new GetUploadUrlRequest().Send((response) =>
            //Start coroutine and pass in the upload url
    //Our coroutine takes a screenshot of the game
    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);
        //This basically takes a screenshot
        byte[] bytes = tex.EncodeToPNG(); //Can also encode to jpg, just make sure to change the file extensions down below
        // Create a Web Form, this will be our POST method's data
        var form = new WWWForm();
        form.AddField("somefield", "somedata");
        form.AddBinaryData("file", bytes, "screenshot.png", "image/png");
	//POST the screenshot to GameSparks
        WWW w = new WWW(uploadUrl, form); 
        yield return w;
        if (w.error != null)
    //This will be our message listener, this will be triggered when we successfully upload a file
    public void GetUploadMessage(GSMessage message)
        //Every time we get a message
        //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
    public IEnumerator DownloadImage(string downloadUrl)
        var www = new WWW(downloadUrl);
        yield return www;
        downloadedImage = new Texture2D(200, 200);



How I can delete the photo I upload to the server?

Hello,  I am abale to the url but uploading is not working. I have swift code here,   

 func uploadImage(urlString: String!, paramName: String, fileName: String, image: UIImage) {  let url = URL(string: urlString)    // generate boundary string using a unique per-app string  let boundary = UUID().uuidString let session = URLSession.shared    // Set the URLRequest to POST and to the specified URL  var urlRequest = URLRequest(url: url!)  urlRequest.httpMethod = "POST"    // Set Content-Type Header to multipart/form-data, this is equivalent to submitting form data with file upload in a web browser  // And the boundary is also set here  urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")  var data = Data() // Add the image data to the raw http request data  data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)  data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)  data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)  data.append(image.pngData()!)  data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)    // Send a POST request to the URL, with the data we created earlier  session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in  self.hideActivity()  if error == nil {  let jsonData = try? JSONSerialization.jsonObject(with: responseData!, options: .allowFragments)  if let json = jsonData as? [String: Any] {  print(json)  }  }  }).resume()  }

Do you need to authenticate a user or anything else before this code? mine does not seem to work.


that was a very useful read. i have a number of uses for this thank you for sharing

How I can delete the photo I upload to the server?

Hi Luis,

You can use SparkFiles deleteUploadedFile call to remove user uploaded files. You can read more about this here.



Another user can access to that url?? 


Login to post a comment