Fork me on GitHub

C#.NET使用multipart/form-data方式上传文件及参数

public static string UploadPeopleFaceRequest(AddVisitorRequestDto addVisitorRequestDto)
{
    try
    {
        string url = _faceIp + "/fastgate/visitor";
        Dictionary<string, object> parameters = new Dictionary<string, object>();
        parameters.Add("PeoName", addVisitorRequestDto.PeoName);
        parameters.Add("PeoSex", addVisitorRequestDto.PeoSex);
        parameters.Add("PeoCardType", addVisitorRequestDto.PeoCardType);
        parameters.Add("PeoCardNum", addVisitorRequestDto.PeoCardNum);
        parameters.Add("PeoTelephone", addVisitorRequestDto.PeoTelephone);
        parameters.Add("file", addVisitorRequestDto.file);
        parameters.Add("PeoStartTime", addVisitorRequestDto.PeoStartTime);
        parameters.Add("PeoEndTime", addVisitorRequestDto.PeoEndTime);
        parameters.Add("AddImagesUrl", addVisitorRequestDto.AddImagesUrl);
        parameters.Add("PeoPersonName", addVisitorRequestDto.PeoPersonName);
        parameters.Add("PersonPhone", addVisitorRequestDto.PersonPhone);
        //parameters.Add("Qrcode", addVisitorRequestDto.Qrcode);

        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        request.Method = "POST";
        request.KeepAlive = true;
        var curCookie = GetToken();     //获取cookie
        request.Headers.Add("cookie", curCookie);
        //request.Credentials = System.Net.CredentialCache.DefaultCredentials;

        if (parameters != null && parameters.Count > 0)
        {
            using (Stream requestStream = request.GetRequestStream())
            {
                foreach (KeyValuePair<string, object> pair in parameters)
                {
                    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    if (pair.Value is AddVisitorRequestDto.FormFile)  //如果是文件的格式
                    {
                        AddVisitorRequestDto.FormFile file = pair.Value as AddVisitorRequestDto.FormFile;
                        string header = "Content-Disposition: form-data; name=\"" + pair.Key + "\"; filename=\"" + file.Name + "\"\r\nContent-Type: " + file.ContentType + "\r\n\r\n";
                        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(header);
                        requestStream.Write(bytes, 0, bytes.Length);
                        byte[] buffer = new byte[32768];
                        int bytesRead;
                        if (file.Stream == null)
                        {
                            // upload from file
                            using (FileStream fileStream = File.OpenRead(HttpContext.Current.Server.MapPath(file.FilePath)))
                            {
                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                    requestStream.Write(buffer, 0, bytesRead);
                                fileStream.Close();
                            }
                        }
                        else
                        {
                            // upload from given stream
                            while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
                                requestStream.Write(buffer, 0, bytesRead);
                        }
                    }
                    else
                    {
                        string data = "Content-Disposition: form-data; name=\"" + pair.Key + "\"\r\n\r\n" + pair.Value;
                        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
                        requestStream.Write(bytes, 0, bytes.Length);
                    }
                }

                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                requestStream.Write(trailer, 0, trailer.Length);
                requestStream.Close();
            }
        }

        using (WebResponse response = request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    var returnRes = reader.ReadToEnd();
                    BaseHelper.WriteLogs("门禁人脸上传返回", returnRes);

                    return returnRes;
                }
            }
        }
    }
    catch (Exception ex)
    {
        BaseHelper.WriteLogs("门禁人脸上传返回", ex.Message);
    }

    return null;
}

  

posted @ 2023-11-01 09:32  WantRemake  阅读(1259)  评论(0编辑  收藏  举报