Unity/C# multipart/form-data 提交文件和参数

参考链接:https://blog.csdn.net/qq_34611658/article/details/105530402

 /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="url"><服务器地址>
    /// <param name="dic"></param>
    /// <param name="filepath"><文件的本地储存地址>
    /// <param name="filename"><文件的名字>
    /// <returns></returns>
    public static string PostJsonData(string url, Dictionary<string, string> dic, string filepath, string filename)
    {
        string str = "";
        try
        {
            HttpClient client = new HttpClient();
            var postContent = new MultipartFormDataContent();
            string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
            postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
            postContent.Headers.Add("unionId", UserInfo.UnionId);
            postContent.Headers.Add("token", UserInfo.User_Token);
            string filekeyname = "file";
            postContent.Add(new ByteArrayContent(File.ReadAllBytes(filepath)), filekeyname, filename);
            foreach (var key in dic.Keys)
            {
                postContent.Add(new StringContent(dic[key].ToString()), key);
            }
            HttpResponseMessage response = client.PostAsync(url, postContent).Result;
            str = response.Content.ReadAsStringAsync().Result;
        }
        catch (Exception ex)
        {
            Debug.LogError("PostJsonData:" + ex.ToString());
        }
        return str;
    }

调用

Dictionary<string, string> keyValues = new Dictionary<string, string>();
keyValues.Add("cert", cert);//cert是服务器返回的凭证  这里的凭证只是针对这个项目后端人员定义的
string result = PostJsonData(url, keyValues, path, filename);

下图是后端给的参数值:
图中参数名称file对应代码中的filekeyname **加粗样式**
添加:截屏上传至服务器
起截图名字的时候记得加后缀(.png/.jpg)

要在 Unity 中使用 UnityWebRequest 上传带有时间字段文件名字段的文件,您可以使用以下代码: ```csharp IEnumerator UploadFile(string url, string filePath, string fileName) { // Create a new UnityWebRequest UnityWebRequest request = UnityWebRequest.Post(url, new List<IMultipartFormSection>()); // Set the content type request.SetRequestHeader("Content-Type", "multipart/form-data"); // Create a new MultipartFormDataSection for the file byte[] fileData = File.ReadAllBytes(filePath); MultipartFormDataSection fileSection = new MultipartFormDataSection("file", fileData, fileName, "application/octet-stream"); // Add the file section to the request request.multipartFormData.Add(fileSection); // Add the time field to the request request.AddField("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); // Set the upload handler request.uploadHandler = new UploadHandlerRaw(request.multipartFormData.CreateByteArray()); // Set the download handler request.downloadHandler = new DownloadHandlerBuffer(); // Send the request yield return request.SendWebRequest(); // Check for errors if (request.result != UnityWebRequest.Result.Success) { Debug.LogError(request.error); } else { Debug.Log("File uploaded successfully"); } } ``` 要在 C# 中使用 HttpListener 接收带有时间字段文件名字段的文件,您可以使用以下代码: ```csharp HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); while (true) { HttpListenerContext context = listener.GetContext(); if (context.Request.HttpMethod == "POST") { // Get the time field value string time = context.Request.Form["time"]; // Get the file field values HttpFileCollection files = context.Request.Files; HttpPostedFile file = files[0]; string fileName = file.FileName; Stream fileStream = file.InputStream; // Save the file using (FileStream output = new FileStream(fileName, FileMode.Create)) { fileStream.CopyTo(output); } // Send a response context.Response.StatusCode = 200; context.Response.Close(); } } ``` 请注意,这只是一个基本示例代码,您需要根据您的具体需求进行修改。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值