I am currently trying to make a post request with a file attached to the form but I found out that it is not the file I have attached but just the path to the file.
My question is how do I get this file and attach it to the form?
Here is my code so far:
string altPath = Path.Combine(Application.persistentDataPath, "nice-work.wav");
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormFileSection("wavfile", altPath));
UnityWebRequest uwr = UnityWebRequest.Post(url, formData);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " uwr.error);
}
else
{
Debug.Log("Received: " uwr.downloadHandler.text);
}
the variable altPath is the path but not the file and this leads to failed post request.
CodePudding user response:
If you look at MultipartFormFileSection
the constructor you are currently using is
MultipartFormFileSection(string data, string fileName)
which is of course not what you want to do.
You rather have to actually read the according file content e.g. simply using File.ReadAllBytes
...
var multiPartSectionName = "wavfile";
var fileName = "nice-work.wav";
var altPath = Path.Combine(Application.persistentDataPath, fileName);
var data = File.ReadAllBytes(altPath);
var formData = new List<IMultipartFormSection>
{
new MultipartFormFileSection(multiPartSectionName, data, fileName)
};
...
or depending on your server side needs
...
var formData = new List<IMultipartFormSection>
{
new MultipartFormFileSection(fileName, data)
};
...
Though have in mind that ReadAllBytes
is a synchronous (blocking) call and for larger files you might rather want to use some asynchronous approach.