unity3d Post (Upload A File)


Example

Upload a file to server is also a post. You can easily upload a file through WWW, like the below:

Upload A Zip File To Server

string mainUrl = "http://server/upload/";
string saveLocation;

void Start() 
{
    saveLocation = "ftp:///home/xxx/x.zip"; // The file path.
    StartCoroutine(PrepareFile());
}

// Prepare The File.
IEnumerator PrepareFile() 
{
    Debug.Log("saveLoacation = " + saveLocation);
     
    // Read the zip file.
    WWW loadTheZip = new WWW(saveLocation);

    yield return loadTheZip;

    PrepareStepTwo(loadTheZip);
}

void PrepareStepTwo(WWW post) 
{
    StartCoroutine(UploadTheZip(post));
}

// Upload.
IEnumerator UploadTheZip(WWW post) 
{
    // Create a form.
    WWWForm form = new WWWForm();
 
    // Add the file.
    form.AddBinaryData("myTestFile.zip",post.bytes,"myFile.zip","application/zip");
 
    // Send POST request.
    string url = mainUrl;
    WWW POSTZIP = new WWW(url,form);
 
    Debug.Log("Sending zip...");
    yield return POSTZIP;
    Debug.Log("Zip sent!");
}

In this example, it use the coroutine to prepare and upload the file, if you want to know more about Unity coroutines, please visit Coroutines.