今天调用某API时,对于文档中的传入参数:File[] 类型,感觉很陌生,无从下手! 按通常的方式在json参数中加入file的二进制数据提交,一直报错(参数错误)!后来经过多方咨询,是要换一种

表单提交方式,即:模拟提交带附件的表单!在网上扒出了一个用于提交带附件表单的类!使用方法如下:

使用  参考代码(工具类代码在下面):

                //构造文件
FormUpload.FileParameter file = new FormUpload.FileParameter(File.ReadAllBytes("D://TestAdvertiserFile.jpg"), "TestAdvertiserFile.jpg"); //构造参数
Dictionary<string, object> postParams = new Dictionary<string, object>();
postParams.Add("demoId", );
postParams.Add("token", "TnQqQSDFSDI#2121231");
postParams.Add("advertiserId", input.SinaInput.Id);
postParams.Add("name", input.SinaInput.Name);
postParams.Add("industry",input.SinaInput.Industry); //文件作为参数加入,如果有多个文件,可以参照加入多个
postParams.Add("qualificationFiles", file); //提交请求,获得返回结果
var httpWebResp = FormUpload.MultipartFormDataPost("http://amp.ad.sina.com.cn/sax/interface/advertiser/upload.action", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.3 Safari/535.19", postParams); Stream instream = httpWebResp.GetResponseStream();
StreamReader sr = new StreamReader(instream,Encoding.UTF8);
//返回结果网页(html)代码
string response = sr.ReadToEnd();
sr.Close();

工具类如下:

    // Implements multipart/form-data POST in C# http://www.ietf.org/rfc/rfc2388.txt
// http://www.briangrinstead.com/blog/multipart-form-post-in-c
public static class FormUpload
{
private static readonly Encoding encoding = Encoding.UTF8; public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
{
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
string contentType = "multipart/form-data; boundary=" + formDataBoundary; byte[] formData = GetMultipartFormData(postParameters, formDataBoundary); return PostForm(postUrl, userAgent, contentType, formData);
} private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
{
HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest; if (request == null)
{
throw new NullReferenceException("request is not a http request");
} // Set up the request properties.
request.Method = "POST";
request.ContentType = contentType;
request.UserAgent = userAgent;
request.CookieContainer = new CookieContainer();
request.ContentLength = formData.Length; // You could add authentication here as well if needed:
// request.PreAuthenticate = true;
// request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
// request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password"))); // Send the form data to the request.
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, , formData.Length);
requestStream.Close();
} return request.GetResponse() as HttpWebResponse;
} private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false; foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
formDataStream.Write(encoding.GetBytes("\r\n"), , encoding.GetByteCount("\r\n")); needsCLRF = true; if (param.Value is FileParameter)
{
FileParameter fileToUpload = (FileParameter)param.Value; // Add just the first part of this param, since we will write the file data directly to the Stream
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream"); formDataStream.Write(encoding.GetBytes(header), , encoding.GetByteCount(header)); // Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileToUpload.File, , fileToUpload.File.Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
formDataStream.Write(encoding.GetBytes(postData), , encoding.GetByteCount(postData));
}
} // Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(encoding.GetBytes(footer), , encoding.GetByteCount(footer)); // Dump the Stream into a byte[]
formDataStream.Position = ;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, , formData.Length);
formDataStream.Close(); return formData;
} public class FileParameter
{
public byte[] File { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public FileParameter(byte[] file) : this(file, null) { }
public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
public FileParameter(byte[] file, string filename, string contenttype)
{
File = file;
FileName = filename;
ContentType = contenttype;
}
}
}

C# 模拟提交带附件(input type=file)的表单的更多相关文章

  1. input type="file"多图片上传 原生html传递的数组集合

    单个的input type="file"表单也是可以实现多图片上传的 代码如下: <form action="manypic.php" method=&q ...

  2. input type="file"多图片上传

    单个的input type="file"表单也是可以实现多图片上传的 代码如下: <form action="manypic.php" method=&q ...

  3. salesforce零基础学习(八十九)使用 input type=file 以及RemoteAction方式上传附件

    在classic环境中,salesforce提供了<apex:inputFile>标签用来实现附件的上传以及内容获取.salesforce 零基础学习(二十四)解析csv格式内容中有类似的 ...

  4. 模拟input type=file

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. 【原创】js中input type=file的一些问题

    1.介绍 在开发中,文件上传必不可少,input[type=file] 是常用的上传标签,但是它长得又丑.浏览的字样不能换,但是他长得到底有多丑呢.我们来看看在不同浏览器里的样子吧. <inpu ...

  6. 文件上传按钮input[type="file"]按钮美化时在IE8中的bug【兼容至IE8】

    首先看一下完成后的效果,鼠标移入可改变为手指的效果. 在此就不加图标了 <label class="file-upload"> <span>上传附件< ...

  7. <input type="file"> 标签详解

    详见:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/Input/file#attr-multiple 使用 type=" ...

  8. input type='file'上传控件假样式

    采用bootstrap框架样式 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> &l ...

  9. HTML <input type="file">上传文件——结合asp.net的一个文件上传示例

    HTML的代码:(关键是要在form里设置enctype="multipart/form-data",这样才能在提交表单时,将文件以二进制流的形式传输到服务器) 一. <fo ...

随机推荐

  1. 领域驱动设计系列(2)浅析VO、DTO、DO、PO的概念、区别和用处

    PO:persistant object持久对象 最形象的理解就是一个PO就是数据库中的一条记录.好处是可以把一条记录作为一个对象处理,可以方便的转为其它对象. BO:business object业 ...

  2. HEVC与VP9编码效率对比

    HEVC(High EfficiencyVideo Coding,高效率视频编码)是一种视频压缩标准,H.264/MPEG-4 AVC的继任者.目前正在由ISO/IEC MPEG和ITU-T VCEG ...

  3. 在SSIS包中使用 Checkpoint从失败处重新启动包

    使用SSIS做ETL的过程中会遇到各种各样的错误,对于一些大数据量的Job失败以后我们不希望重新运行,因为重新运行的时间开销是非常大的,我们只希望从失败的部分开始运行,这样可以省去很多的时间. SSI ...

  4. protobuf 中的嵌套消息的使用

    protobuf的简单的使用,不过还留下了一个问题,那就是之前主要介绍的都是对简单数据的赋值,简单数据直接采用set_xx()即可,但是如果不是简单变量而是自定义的复合类型变量,就没有简单的set函数 ...

  5. linux下curl编程

    LibCurl是免费的客户端URL传输库,支持FTP,FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, FILE ,LDAP等协议,其主页是http: ...

  6. 在MySQL中创建实现自增的序列(Sequence)的教程

    这篇文章主要介绍了在MySQL中创建实现自增的序列(Sequence)的教程,分别列举了两个实例并简单讨论了一些限制因素,需要的朋友可以参考下 项目应用中,曾有以下一个场景: 接口中要求发送一个int ...

  7. android的快速开发框架集合

    出自:http://blog.csdn.net/shulianghan/article/details/18046021 1.Afinal  (快速开发框架) 简介:http://www.oschin ...

  8. JAVA 对象内存分析

    1.jmap -heap pid 或者 jmap -histo pid 2.jmap -dump:file=folder/dumpFileName.txt,format=b pid 3.对3的输出文件 ...

  9. PHP的排列组合问题 分别从每一个集合中取出一个元素进行组合,问有多少种组合?

    首先说明这是一个数学的排列组合问题C(m,n) = m!/(n!*(m-n)!) 比如:有集合('粉色','红色','蓝色','黑色'),('38码','39码','40码'),('大号','中号') ...

  10. object-c 协议(Protocols)和代理(Delegation)的学习

    代理是Object-C中的一个重要机制,他可以将面向对象编程的封装特性进一步加强,不是自己负责的事情坚决不做,而是转而让对应的事情负责人(代理)去做.相反如果是自己需要负责的事情(作为别人的代理),会 ...