加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#客户端使用 http form的post方法提交图片

发布时间:2020-12-15 17:53:47 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 一、封装的类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; namesp

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

一、封装的类
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    using System.Net;  
    using System.IO;  
      
    namespace WpfApplication1  
    {  
        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;  
                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 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("rn"),encoding.GetByteCount("rn"));  
      
                    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}rnContent-Disposition: form-data; name="{1}"; filename="{2}"rnContent-Type: {3}rnrn",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}rnContent-Disposition: form-data; name="{1}"rnrn{2}",param.Value);  
                        formDataStream.Write(encoding.GetBytes(postData),encoding.GetByteCount(postData));  
                    }  
                }  
      
                // Add the end of the request.  Start with a newline  
                string footer = "rn--" + boundary + "--rn";  
                formDataStream.Write(encoding.GetBytes(footer),encoding.GetByteCount(footer));  
      
                // Dump the Stream into a byte[]  
                formDataStream.Position = 0;  
                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,string filename,string contenttype)  
                {  
                    File = file;  
                    FileName = filename;  
                    ContentType = contenttype;  
                }  
            }  
        }  
    }   
    Dictionary<string,object> postParameters = new Dictionary<string,object>();  
      
                postParameters.Add("paramA","value1");  
                postParameters.Add("paramB","value2");  
                postParameters.Add("paramC","value3");  
      
                postParameters.Add("picture",new FormUpload.FileParameter(data,"11.jpg","image/jpg"));  
      
                // Create request and receive response  
                string postURL = global_ip + "service/PostImageAsBinty/";  
                string userAgent = "Someone";  
                HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL,postParameters);  
      
                // Process response  
                StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());  
                string fullResponse = responseReader.ReadToEnd();  
                webResponse.Close();  


以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读