C# HttpWebRequest 传文件及参数

C# 后台调用api 传文件及参数,记录下也是网上找的,用起来没问题,接口端用的是Java

 public static string webPost(string apiurl,string fpath, string classCode,  int code, string time)
        {
            NameValueCollection poststring = new NameValueCollection();
          
            poststring["classCode"] = classCode;           
            poststring["code"] = code.ToString();
            poststring["recordTime"] = time;
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = Encoding.ASCII.GetBytes("
--" + boundary + "
");
            byte[] endbytes = Encoding.ASCII.GetBytes("
--" + boundary + "--
");

            //1.HttpWebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiurl);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Credentials = CredentialCache.DefaultCredentials;

            using (Stream stream = request.GetRequestStream())
            {
                //1.1 key/value
                string formdataTemplate = "Content-Disposition: form-data; name="{0}"

{1}";
                if (poststring != null)
                {
                    foreach (string key in poststring.Keys)
                    {
                        stream.Write(boundarybytes, 0, boundarybytes.Length);
                        string formitem = string.Format(formdataTemplate, key, poststring[key]);
                        byte[] formitembytes = Encoding.GetEncoding("UTF-8").GetBytes(formitem);
                        stream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }

                //1.2 file
                string headerTemplate = "Content-Disposition: form-data; name="{0}"; filename="{1}"
Content-Type: application/octet-stream

";
                byte[] buffer = new byte[4096];
                int bytesRead = 0;

                stream.Write(boundarybytes, 0, boundarybytes.Length);
                string header = string.Format(headerTemplate, "vFile", Path.GetFileName(fpath));
                byte[] headerbytes = Encoding.GetEncoding("UTF-8").GetBytes(header);
                stream.Write(headerbytes, 0, headerbytes.Length);
                using (FileStream fileStream = new FileStream(fpath, FileMode.Open, FileAccess.Read))
                {
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        stream.Write(buffer, 0, bytesRead);
                    }
                }

                //1.3 form end
                stream.Write(endbytes, 0, endbytes.Length);
            }
            //2.WebResponse
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                return stream.ReadToEnd();
            }
        }
    }

Java 接收

 @RequestMapping(value = "/uploadSliceVideoFromScreen")
    public ResultBean uploadSliceVideoFromScreen(@RequestParam(value="vFile")MultipartFile vFile,
                                                  String classCode, String code, String recordTime, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
           
            TODO something........
            response.setStatus(200);
            return ResultBean.success();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            return ResultBean.failMessage("上传失败,请重试");
        }
    }

  

原文地址:https://www.cnblogs.com/Vagrant-Wind/p/12055451.html