zoukankan      html  css  js  c++  java
  • 使用HttpWebRequest POST上传文件

    2019/10/27, .Net c#代码片段

    摘要:使用HttpWebRequest向Api接口发送文件,multipart-form数据格式,POST方式
    参考地址

    /// <summary>
    /// HttpWebRequest发送文件
    /// </summary>
    /// <param name="url">url</param>
    /// <param name="filePath">文件路径</param>
    /// <param name="paramName">文件参数名</param>
    /// <param name="contentType">contentType</param>
    /// <param name="nameValueCollection">其余要附带的参数键值对</param>
    public static void HttpUploadFile(string url, string filePath, string paramName, string contentType, NameValueCollection nameValueCollection)
    {
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("
    --" + boundary + "
    ");
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        request.Method = "POST";
        request.KeepAlive = true;
        request.Credentials = CredentialCache.DefaultCredentials;
        Stream requestStream = request.GetRequestStream();
        string formdataTemplate = "Content-Disposition: form-data; name="{0}"
    
    {1}";
        foreach (string key in nameValueCollection.Keys)
        {
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, key, nameValueCollection[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            requestStream.Write(formitembytes, 0, formitembytes.Length);
        }
        requestStream.Write(boundarybytes, 0, boundarybytes.Length);
        string header = string.Format("Content-Disposition: form-data; name="{0}"; filename="{1}"
    Content-Type: {2}
    
    ", paramName, filePath, contentType);
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        requestStream.Write(headerbytes, 0, headerbytes.Length);
        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            requestStream.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();
        byte[] trailer = System.Text.Encoding.ASCII.GetBytes("
    --" + boundary + "--
    ");
        requestStream.Write(trailer, 0, trailer.Length);
        requestStream.Close();
        WebResponse webResponse = null;
        try
        {
            webResponse = request.GetResponse();
            Stream responseStream = webResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream);
            string result = streamReader.ReadToEnd();
        }
        catch (Exception ex)
        {
            if (webResponse != null)
            {
                webResponse.Close();
                webResponse = null;
            }
        }
        finally
        {
            request = null;
        }
    }
    

    使用

    NameValueCollection nvc = new NameValueCollection();
    nvc.Add("id", "1000");
    nvc.Add("name", "user1");
    HttpUploadFile("http://your.server.com/upload",@"C:	est	est.jpg", "file", "image/jpeg", nvc);
    
  • 相关阅读:
    Spring Boot 配置加载顺序详解
    JVM总结篇
    nginx负载均衡的策略
    布隆过滤器的方式解决缓存穿透问题
    Spring Cloud Eureka自我保护机制(服务无法剔除)
    缓存穿透,缓存击穿,缓存雪崩解决方案分析
    高并发秒杀系统总结
    Linux环境进程间通信(一)
    HDU 1695 GCD(容斥定理)
    数据结构精要------冒泡与直接排序算法
  • 原文地址:https://www.cnblogs.com/kasnti/p/11748041.html
Copyright © 2011-2022 走看看