Unity上传文件失败,但是python上传就能成功

需求POST请求上传一个文件和两个字段
问题Python requests 上传能够成功,使用Unity写上传失败

抓包发现Python和Unity程序里 发送的请求里字段格式不同


左边为python 右边为unity中默认请求

修改写法为如下成功

BestHttp插件写法

    MultipartFormDataStream multipartFormDataStream = new MultipartFormDataStream(request);
    multipartFormDataStream.AddStreamField(new MemoryStream(Encoding.UTF8.GetBytes(user_id)),"user_id");
    multipartFormDataStream.AddStreamField(new MemoryStream(Encoding.UTF8.GetBytes(game_id)), "game_id");
    multipartFormDataStream.AddStreamField(new MemoryStream(file), "file", imageName, "image/png");

UnityWebRequest 写法

IEnumerator UnityUpload()
{
    List formdatas = new List();

    MultipartFormDataSection multipartFormDataSection1 = new MultipartFormDataSection("user_id", Encoding.UTF8.GetBytes(userid));
    MultipartFormDataSection multipartFormDataSection2 = new MultipartFormDataSection("game_id", Encoding.UTF8.GetBytes(gameid));
    MultipartFormFileSection multipartFormFileSection = new MultipartFormFileSection("file", File.ReadAllBytes(imagePath), "000001.png", "image/png");

    formdatas.Add(multipartFormDataSection1);
    formdatas.Add(multipartFormDataSection2);
    formdatas.Add(multipartFormFileSection);

    UnityWebRequest webRequest = UnityWebRequest.Post(UploadAddr, formdatas);

    yield return webRequest.SendWebRequest();

    if (webRequest.error == null)
    {
        Debug.Log("请求完成:"+webRequest.downloadHandler.text);
    }
    else
    {
        Debug.LogError("上传失败:"+webRequest.error);
    }

}

你可能感兴趣的:(Unity上传文件失败,但是python上传就能成功)