zoukankan      html  css  js  c++  java
  • 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", 3);
                    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, 0, 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("
    "), 0, encoding.GetByteCount("
    "));
    
                    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}
    Content-Disposition: form-data; name="{1}"; filename="{2}";
    Content-Type: {3}
    
    ",
                            boundary,
                            param.Key,
                            fileToUpload.FileName ?? param.Key,
                            fileToUpload.ContentType ?? "application/octet-stream");
    
                        formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
    
                        // Write the file data directly to the Stream, rather than serializing it to a string.
                        formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
                    }
                    else
                    {
                        string postData = string.Format("--{0}
    Content-Disposition: form-data; name="{1}"
    
    {2}",
                            boundary,
                            param.Key,
                            param.Value);
                        formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
                    }
                }
    
                // Add the end of the request.  Start with a newline
                string footer = "
    --" + boundary + "--
    ";
                formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
    
                // Dump the Stream into a byte[]
                formDataStream.Position = 0;
                byte[] formData = new byte[formDataStream.Length];
                formDataStream.Read(formData, 0, 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;
                }
            }
        }
  • 相关阅读:
    (转)怎样获得与激活Windows 7超级管理员权限
    (转) C代码优化方案
    英语词汇立体记忆 02
    (转)LUA和C之间的函数调用
    通过lua自带例子学习lua 01
    英语词汇立体记忆 01
    反射(类加载内存分析)
    反射(类加载器的作用)
    反射(动态创建对象操作属性)
    反射(分析类初始化)
  • 原文地址:https://www.cnblogs.com/yako/p/3171801.html
Copyright © 2011-2022 走看看