- Home /
Question by
Saulius · Apr 29, 2018 at 08:16 PM ·
webrequestupload
MultipartFormFileSection not adding files to the webrequest! Need some guidance how to solve it.
My API keeps telling me that no files where uploaded when using Unity app. Everything works perfect when testing with postman. I had no problems with WWW class when uploading files, but since I wrote API plugin I want to use UnityWebRequest. I would really appreciate if someone could help me. I attached wireshark data and my code.
IEnumerator FileUploadRequest (Request request)
{
request.Processing = true;
Response response = new Response ();
List<FileUpload> files = (List<FileUpload>)request.additionData;
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
for (int cnt = 0; cnt < files.Count; cnt++)
{
Debug.Log(files[cnt].Bytes.Length + " " + "bytes loaded");
formData.Add(new MultipartFormFileSection("files[]", files[cnt].Bytes));
}
var webRequest = UnityWebRequest.Post (RootURL + "/" + request.EndPoint,formData);
webRequest.chunkedTransfer = false;
foreach (KeyValuePair<string, string> entry in request.requestHeaders) {
webRequest.SetRequestHeader (entry.Key, entry.Value);
}
if (request.progress != null)
request.progress.Invoke (webRequest.uploadHandler.progress);
yield return webRequest.SendWebRequest ();
request.Processing = false;
if (webRequest.isNetworkError) {
Debug.Log ("Something went wrong, and returned error: " + webRequest.error);
} else {
// process results
response.body = webRequest.downloadHandler.text;
response.code = (ResponseCode)Enum.ToObject (typeof(ResponseCode), webRequest.responseCode);
response.headers = webRequest.GetResponseHeaders ();
Debug.LogWarning ("URL:" + webRequest.url + " " + ResponseMsg (response));
if (request.callback != null)
request.callback.Invoke (response);
}
OnRequestDone ();
webRequest.Dispose ();
}
Actual request here:
public void Upload()
{
if (fileChooseHandler.filePath != string.Empty)
{
FileUpload file = new FileUpload();
file.Bytes = File.ReadAllBytes(fileChooseHandler.filePath);
Request req = new Request(RequestType.FILE_UPLOAD);
req.progress = (x) => { Debug.Log(x); };
req.AuthRequired = true;
req.EndPoint = "upload";
List<FileUpload> files = new List<FileUpload>();
files.Add(file);
req.additionData = (object)files;
req.callback += APIResponse;
api.MakeRequest(req);
}
}
screenshot-3.png
(304.0 kB)
Comment