Generic/unknown HTTP error when uploading files to

2019-08-16 23:06发布

问题:

I have an HTML page with a form for uploading files to SmartFile. Below is the piece of C# code that I am using to upload the files from my game in Unity to this url.

WWWForm fileForm = new WWWForm();
string[] files = Directory.GetFiles(".", "*.txt");
fileForm.AddField("file", files[0]);
WWW www = new WWW("https://file.ac/xySSFOicMMk", fileForm);            

Unfortunately it is leading to the below exception. What is wrong here?

Connection error while sending analytics... Error:415 Unsupported Media Type UnityEngine.Debug:LogError(Object) c__Iterator0:MoveNext() (at Assets/Survey/Survey.cs:99) UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

Update 1:- I changed the 3rd line to fileForm.AddBinaryData("file", File.ReadAllBytes(files[i]), files[i], "text/plain");

I'm not getting the error anymore, but still can't see the file getting uploaded, even though www.isDone is returning true.

Update 2:- Tried the UnityWebRequest API as well, it led to

Generic/unknown HTTP error (400 response code)

List<IMultipartFormSection> formData = new List<IMultipartFormSection>();           
byte[] bytes = File.ReadAllBytes(files[0]);
files[0] = files[0].Replace(@".\","");      
formData.Add(new MultipartFormFileSection("file", bytes, files[0], "text/plain"));
StartCoroutine(UploadFile(formData));  
IEnumerator UploadFile(List<IMultipartFormSection> formData)
{       
    UnityWebRequest www = UnityWebRequest.Post("https://file.ac/xySSFOicMMk", formData);
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        Debug.Log(www.error);
    }
    else
    {
        Debug.Log("Form upload complete!");
    }
}

UnityWebRequest.Post does not seem to work either with WWWForm' orList` in the Unity version 2017.3.1f1 (64-bit)

回答1:

Used the HttpWebRequest with the solution found here alongwith this to fix the certificate error in Unity and finally had some peace of mind. Entire solution is posted here - https://pastebin.com/wNQ46s0H

Seems like in order for WWWForm to work, you need to have both the binary and non-binary data in your form - HttpWebRequest post paramaters for AWS file upload request, leading to 400 error