C# 模拟提交带附件(input type=file)的表单
今天调用某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)的表单的更多相关文章
- input type="file"多图片上传 原生html传递的数组集合
单个的input type="file"表单也是可以实现多图片上传的 代码如下: <form action="manypic.php" method=&q ...
- input type="file"多图片上传
单个的input type="file"表单也是可以实现多图片上传的 代码如下: <form action="manypic.php" method=&q ...
- salesforce零基础学习(八十九)使用 input type=file 以及RemoteAction方式上传附件
在classic环境中,salesforce提供了<apex:inputFile>标签用来实现附件的上传以及内容获取.salesforce 零基础学习(二十四)解析csv格式内容中有类似的 ...
- 模拟input type=file
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 【原创】js中input type=file的一些问题
1.介绍 在开发中,文件上传必不可少,input[type=file] 是常用的上传标签,但是它长得又丑.浏览的字样不能换,但是他长得到底有多丑呢.我们来看看在不同浏览器里的样子吧. <inpu ...
- 文件上传按钮input[type="file"]按钮美化时在IE8中的bug【兼容至IE8】
首先看一下完成后的效果,鼠标移入可改变为手指的效果. 在此就不加图标了 <label class="file-upload"> <span>上传附件< ...
- <input type="file"> 标签详解
详见:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/Input/file#attr-multiple 使用 type=" ...
- input type='file'上传控件假样式
采用bootstrap框架样式 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> &l ...
- HTML <input type="file">上传文件——结合asp.net的一个文件上传示例
HTML的代码:(关键是要在form里设置enctype="multipart/form-data",这样才能在提交表单时,将文件以二进制流的形式传输到服务器) 一. <fo ...
随机推荐
- JWPlayer 初探
http://www.360doc.com/content/13/0103/22/21412_258041878.shtml JWPlayer 是一款比较实用的web flash 播放器
- kbengine环境搭建(2)
做好准备工作后,可以开始搭建我们的kbengine服务端,运行成功kbengine服务端,共有9个服务会相应的被打开,并会全部提示[info]found all components! 准备工作 1. ...
- SGU 319 Kalevich Strikes Back(线段树扫描线)
题目大意: n个矩形,将一个大矩形分成 n+1 块.矩形之间不重合,可是包括.求这n+1个矩形的面积 思路分析: 用线段树记录他们之间的父子关系.然后dfs 计算面积. 当给出的矩形上边的时候,就要记 ...
- Android 实现左右滑动效果ViewFlipper终结【转】
本示例演示在Android中实现图片左右滑动效果. 关于滑动效果,在Android中用得比较多,本示例实现的滑动效果是使用ViewFlipper来实现的,当然也可以使用其它的View来实现.接下来 ...
- #pragma的用法
在所有的预处理指令中,#Pragma 指令可能是最复杂的了,它的作用是设定编译器的状态或者是指示编译器完成一些特定的动作.#pragma指令对每个编译器给出了一个方法,在保持与C和 C++语言完全 ...
- 在CG/HLSL中访问着色器属性(Properties)
在CG/HLSL中访问着色器属性 Shader在Properties块中访问材质属性.如果你想在一个着色程序中访问一些属性,你需要声明一个Cg/HLSL具有相同的名称和一个匹配的类型的变量. Prop ...
- 面试题之HTML 的 form 提交之前如何验证数值文本框的内容全 部为数字? 否则的话提示用户并终止提交?
<!DOCTYPE html> <html> <head> <meta charset="{CHARSET}"> <title ...
- 转帖Jmeter中的几个重要测试指标释义
Aggregate Report 是 JMeter 常用的一个 Listener,中文被翻译为“聚合报告”.今天再次有同行问到这个报告中的各项数据表示什么意思,顺便在这里公布一下,以备大家查阅. 如果 ...
- 常用类库之.NET中的字符串
字符串的特性 .不可变性 由于字符串是不可变的的,每次修改字符串,都是创建了一个单独字符串副本(拷贝了一个字符串副本).之所以发生改变只是因为指向了一块新的地址. .字符串池(只针对字符串常量) 当一 ...
- centos7 ops
默认使用firewall防火墙,不在使用iptables 特点:可以动态加载新设置的规则,而不用重启服务 scp操作: scp localfile user@host:remotedir mysql. ...