栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

来自C#客户端的多部分表单

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

来自C#客户端的多部分表单

这是从我编写的一些示例代码中剪切并粘贴的,希望它能提供基础知识。目前仅支持文件数据和表单数据。

public class PostData{    private List<PostDataParam> m_Params;    public List<PostDataParam> Params    {        get { return m_Params; }        set { m_Params = value; }    }    public PostData()    {        m_Params = new List<PostDataParam>();        // Add sample param        m_Params.Add(new PostDataParam("email", "MyEmail", PostDataParamType.Field));    }    /// <summary>    /// Returns the parameters array formatted for multi-part/form data    /// </summary>    /// <returns></returns>    public string GetPostData()    {        // Get boundary, default is --AaB03x        string boundary = ConfigurationManager.AppSettings["ContentBoundary"].ToString();        StringBuilder sb = new StringBuilder();        foreach (PostDataParam p in m_Params)        { sb.AppendLine(boundary); if (p.Type == PostDataParamType.File) {     sb.AppendLine(string.Format("Content-Disposition: file; name="{0}"; filename="{1}"", p.Name, p.FileName));     sb.AppendLine("Content-Type: text/plain");     sb.AppendLine();     sb.AppendLine(p.Value);       } else {     sb.AppendLine(string.Format("Content-Disposition: form-data; name="{0}"", p.Name));     sb.AppendLine();     sb.AppendLine(p.Value); }        }        sb.AppendLine(boundary);        return sb.ToString();    }}public enum PostDataParamType{    Field,    File}public class PostDataParam{    public PostDataParam(string name, string value, PostDataParamType type)    {        Name = name;        Value = value;        Type = type;    }    public string Name;    public string FileName;    public string Value;    public PostDataParamType Type;}

要发送数据,您需要:

HttpWebRequest oRequest = null;oRequest = (HttpWebRequest)HttpWebRequest.Create(oURL.URL);oRequest.ContentType = "multipart/form-data"; oRequest.Method = "POST";PostData pData = new PostData();byte[] buffer = encoding.GetBytes(pData.GetPostData());// Set content length of our dataoRequest.ContentLength = buffer.Length;// Dump our buffered postdata to the stream, booyahoStream = oRequest.GetRequestStream();oStream.Write(buffer, 0, buffer.Length);oStream.Close();// get the responseoResponse = (HttpWebResponse)oRequest.GetResponse();

希望这很清楚,我已经从一些来源进行了剪切和粘贴以使其更加简洁。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421487.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号