- Home /
How to use UnityWebRequest to upload a File via Invision REST API
Hello There
I've been using UnityWebRequest to succesfully access some REST API endpoints. However when it comes to uploading files I couldn't get it to work and am wondering (this might be a bit of an open-ended question) what I am overlooking. I create a WWWForm like this, filling it with required parameters for the API request:
WWWForm form = new WWWForm();
form.AddField("category", 6);
form.AddField("title", "testing.txt");
form.AddField("description", "Just a file");
form.AddBinaryData("files", data, "testing.txt", "text/plain");
data is the byte array of the file im trying to upload. I then do a UnityWebRequest.Post(url, form)
and set the request headers. However I always end up getting a "NO_FILES" response from the server (No files were supplied). Here's the documentation of the API-Endpoint I'm trying to access (with a short description of the files parameter and error codes): https://invisioncommunity.com/developers/rest-api?endpoint=downloads/files/POSTindex
Instead of WWWForm, I've also tried using a List like this and received the same "NO_FILES" error from the server.
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("category", "6"));
formData.Add(new MultipartFormDataSection("title", "testing.txt"));
formData.Add(new MultipartFormDataSection("description", "Just a file"));
formData.Add(new MultipartFormFileSection("files", data, "testing.txt", "text/plain"));
Thanks!
Hi. According to Invision REST API docs you also need to provide author
id.
Everything else looks fine.
Here is an example that I'm using to upload files to server (not Invision REST API):
IEnumerator UploadFileCo()
{
isProjectUploaded = false;
yield return new WaitForEndOfFrame();
var bytes = System.IO.File.ReadAllBytes(file_full_path);
WWWForm form= new WWWForm();
form.AddField("authToken", WebRequestHandler.i.token);
form.AddField("modelId", objectID);
form.AddField("projectType", "Templates");
form.AddField("categoryId", categoryID);
form.AddBinaryData("file", bytes, file_full_path, "application/zip");
var uwr = UnityWebRequest.Post(api_upload, form);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
Debug.LogFormat("Error while uploading file. Stop upload process. \nError code: <color=red>{1}</color>", uwr.downloadHandler.text, uwr.error);
else
{
// Debug.Log("upload project done: " + uwr.downloadHandler.text);
isProjectUploaded = true;
}
uwr.Dispose();
}