C# HttpWebRequest上传文件到服务器(multipart/form-data)

public bool Add(IList<Sim_FilterParam> entity)
{
    if (entity == null)
    {
        return false;
    }

    // 分段内容
    string reqUrl = JsonrpcHttpClient.MakeRpcUrl(typeof(Sim_FilterParam).Name, "add");

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(reqUrl);

    #region 初始化请求对象

    Encoding encoding = null;
    CookieContainer cookieContainer = null;

    HttpWebClient.SetHttpWebRequest(request, cookieContainer);

    #endregion

    string boundary = string.Format("----WebKitFormBoundary{0}", DateTime.Now.Ticks.ToString("x"));//分隔符, 随机字符串或者使用 GlobalConfig.MakeShortGuid();

    request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

    //请求流
    var postStream = new MemoryStream();

    #region 处理Form表单请求内容

    //是否用Form上传文件
    List<DataItem> diList = BuildDataItemList(entity);
    var formUploadFile = diList != null && diList.Count > 0;
    if (formUploadFile)
    {
        HttpWebClient.SetFormPostStream(postStream, diList, boundary);
    }
    else
    {
        request.ContentType = "application/x-www-form-urlencoded";
    }

    #endregion

    request.ContentLength = postStream.Length;  // 写入流的长度,需要 Check

    #region 输入二进制流

    if (postStream != null)
    {
        postStream.Position = 0;
        //直接写入流
        Stream requestStream = request.GetRequestStream();

        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            requestStream.Write(buffer, 0, bytesRead);
        }

        postStream.Close();//关闭文件访问
    }

    #endregion

    // 获取调用结果
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    if (cookieContainer != null)
    {
        response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
    }

    using (Stream responseStream = response.GetResponseStream())
    {
        using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
        {
            string retString = myStreamReader.ReadToEnd();
            //Debug.WriteLine(retString);
        }
    }

    return true;
}

/// <summary>
/// 数据传输结构
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
private List<DataItem> BuildDataItemList(IList<Sim_FilterParam> entity)
{
    var di = new List<DataItem>();

    if (entity != null)
    {
        foreach (Sim_FilterParam item in entity)
        {
            di.Add(new DataItem()
            {
                Key = "filter",
                FileContent = item.ZipFileStream,
                FileName = item.ZipFileName,
            });
        }
    }

    di.Add(new DataItem()
    {
        Key = "dtoStr",
        Value = JsonHelper.Serialize(entity)
    });

    return di;
}

#region 辅助方法

/// <summary>
/// 默认编码
/// </summary>
public static readonly Encoding DEFAULT_ENCODING = Encoding.UTF8;

/// <summary>
/// Http Method - Get
/// </summary>
public const string HTTP_METHOD_POST = "POST";

/// <summary>
/// Http Request - Accept
/// </summary>
public const string REQUEST_ACCEPT = "*/*";

/// <summary>
/// Http Request - UserAgent
/// </summary>
public const string REQUEST_USERAGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";

/// <summary>
/// Http Request - header - XMLHttpRequest
/// </summary>
public const string REQUEST_HEADER_XMLHTTPREQUEST = "XMLHttpRequest";

/// <summary>
/// 设置请求对象
/// </summary>
/// <param name="request"></param>
/// <param name="cookieContainer"></param>
public static void SetHttpWebRequest(HttpWebRequest request, CookieContainer cookieContainer)
{
    string refererUrl = null;

    request.Method = HTTP_METHOD_POST;
    request.Accept = REQUEST_ACCEPT; //"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";         
    request.KeepAlive = true;
    request.UserAgent = REQUEST_USERAGENT;
    if (!string.IsNullOrEmpty(refererUrl))
        request.Referer = refererUrl;
    if (cookieContainer != null)
        request.CookieContainer = cookieContainer;
    request.Headers["Cookie"] = JsonrpcHttpClient.Cookie;
    request.Headers["client"] = "true";
    request.Headers["X-Requested-With"] = REQUEST_HEADER_XMLHTTPREQUEST;
}

public static void SetFormPostStream(Stream postStream, List<DataItem> diList, string boundary)
{
    //文件数据模板
    string fileFormdata =
        "\r\n--" + boundary +
        "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
        "\r\nContent-Type: application/octet-stream" +
        "\r\n\r\n";
    //文本数据模板
    string dataFormdata =
        "\r\n--" + boundary +
        "\r\nContent-Disposition: form-data; name=\"{0}\"" +
        "\r\n\r\n{1}";
    foreach (var item in diList)
    {
        string formdata = null;
        if (item.IsFile)
        {
            //上传文件
            formdata = string.Format(
                fileFormdata,
                item.Key, //表单键
                item.FileName);
        }
        else
        {
            //上传文本
            formdata = string.Format(
                dataFormdata,
                item.Key,
                item.Value);
        }

        //统一处理
        byte[] formdataBytes = null;

        //第一行不需要换行
        if (postStream.Length == 0)
            formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
        else
            formdataBytes = Encoding.UTF8.GetBytes(formdata);
        postStream.Write(formdataBytes, 0, formdataBytes.Length);

        //写入文件内容
        if (item.FileContent != null && item.FileContent.Length > 0)
        {
            using (var stream = item.FileContent)
            {
                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    postStream.Write(buffer, 0, bytesRead);
                }
            }
        }
    }

    //结尾
    var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
    postStream.Write(footer, 0, footer.Length);
}

#endregion

猜你喜欢

转载自blog.csdn.net/qq_35106907/article/details/85260692