今天调用某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. 5_Navigation Bar

    5 // // ViewController.swift // Navigation Bar // // Created by ZC on 16/1/9. // Copyright © 2016年 Z ...

  2. Mac经常使用快捷键

    Mac使用快捷键会节省非常多时间.使用最多的键就是shift键  option键 command键的组合了.当然一下略微用得多一点点,还有非常多快捷键没一一列举了 进入指定文件夹的一些快捷键 进入 A ...

  3. typedef使用

    1.利用typedef定义函数指针 代码简化,促进跨平台开发 typedef行为有点类似#define 宏,用其实际类型替代同义字.   不同点:typedef 在编译时被解释,因此让编译器来 应付超 ...

  4. 文件下载Demo

    知识点: //获取用户要下载的资源的名称        string name=context.Request.Params["downloadName"];        //设 ...

  5. JavaScript基础(语法类型转换、运算符、语句)

    1.类型转换: 分为自动转换和强制转换,一般用强制转换. 其他类型转换为整数:parseint(): 其他类型转换为小数:parsefloat(): 判断是否是一个合法的数字类型:isNaN(): 是 ...

  6. SPOJ 7001 VLATTICE - Visible Lattice Points(莫比乌斯反演)

    题目链接:http://www.spoj.com/problems/VLATTICE/ 题意:求gcd(a, b, c) = 1    a,b,c <=N 的对数. 思路:我们令函数g(x)为g ...

  7. javascript函数querySelector

    querySelector用于获得dom节点,可以接受三种类型的参数:id(#),class(.),标签.很像jquery的选择器.不过只能返回一个子孙元素,但是jquery选择器的话,可以返回一组元 ...

  8. Android Gradle 配置选项合集

    //让gradle 引入构建安卓app的插件 apply plugin: 'com.android.application' //自定义变量, 使用的时候不需要 ext 前缀 ext { minSdk ...

  9. RAW模板开发--入口文件官方规范

    每个人都有自己的习惯,为了RAW模板能进一步推广,使RAW模板的开发也更有条理,所以写了这个文章. 规范1格式: <?php /*RAW标记声明-start*/ /*RAW标记声明-over*/ ...

  10. 斯坦福 IOS讲义 课件总结 三

    1,@property (nonatomic,readwrite)NSInteger score;注意这里有一个只读和只写的属性,readonly. 2,重写初始化方法也可以改名字和传参数,(改名一般 ...