c# 文件上传,multipart/form-data,btye[]上传附件给java接口

可以联系1204201271qq,直接帮你解决java与c#文件互传的问题。

1.新建一个工具类

//工具类
    public static class FormUpload
    {
        private static readonly Encoding encoding = Encoding.UTF8;

        public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters,string token)
        {
            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,token);
        }

        private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData,string token)
        {
            HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;

            if (request == null)
            {
                throw new NullReferenceException("request is not a http request");
            }
            string access_token = token;
            //if (HttpContext.Current != null)
            //{
            //    access_token = HttpContext.Current.Request.Cookies.Get("access_token").Value;
            //}
            //else
            //{
            //    access_token = System.Web.HttpRuntime.Cache["access_token"].ToString();
            //}

            //request.Headers.Add("Authorization", "Bearer" + access_token);
            request.Headers.Add("Authorization", access_token);

            // 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("\r\n"), 0, 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), 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}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{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 = "\r\n--" + boundary + "--\r\n";
            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;
            }
        }
    }

2.添加post请求代码

 public static string PostFiles(string url, Dictionary<string, object> postParams, string name, string filename,string token, byte[] arraryByte)
        {
            if (filename.Contains("http"))
            {
                //构造文件
                Org.BeijingIT.Common.FormUpload.FileParameter file = new Org.BeijingIT.Common.FormUpload.FileParameter(arraryByte, name);
                postParams.Add("files", file);
                //提交请求,获得返回结果
                var httpWebResp = Org.BeijingIT.Common.FormUpload.MultipartFormDataPost(url, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.3 Safari/535.19", postParams, token);
                Stream instream = httpWebResp.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果网页(html)代码
                string response = sr.ReadToEnd();
                sr.Close();
                return response;
            }
            else
            {
                //构造文件
                Org.BeijingIT.Common.FormUpload.FileParameter file = new Org.BeijingIT.Common.FormUpload.FileParameter(File.ReadAllBytes(filename), name);
                postParams.Add("files", file);
                //提交请求,获得返回结果
                var httpWebResp = Org.BeijingIT.Common.FormUpload.MultipartFormDataPost(url, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.3 Safari/535.19", postParams, token);
                Stream instream = httpWebResp.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果网页(html)代码
                string response = sr.ReadToEnd();
                sr.Close();
                return response;
            }
        }

3.实际调用

string fname = "";
                            string strFileName = "";
                            string lj = 从数据库读取出附件路径,附件分为本地路径和网络路径,需要通过不同的方式下面已经写好了;
                            string filePath = "";
                            byte[] arraryByte = new byte[64 * 1024];
                            if (!lj.Contains("http"))
                            {
                                filePath = lj;
                                filePath = Server.MapPath("~"+ lj);
                                fname = filePath.Substring(filePath.LastIndexOf("\\") + 1, (filePath.LastIndexOf(".") - filePath.LastIndexOf("\\") - 1));//不带拓展名的文件名
                                strFileName = filePath.Substring(filePath.LastIndexOf("\\") + 1, filePath.Length - 1 - filePath.LastIndexOf("\\"));//带拓展名的文件名 
                            }
                            else
                            {
                                filePath =  lj;
                                fname = filePath.Substring(filePath.LastIndexOf("/") + 1, (filePath.LastIndexOf(".") - filePath.LastIndexOf("/") - 1));//不带拓展名的文件名
                                strFileName = filePath.Substring(filePath.LastIndexOf("/") + 1, filePath.Length - 1 - filePath.LastIndexOf("/"));//带拓展名的文件名 
                                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(filePath);
                                request.Method = "Get";
                                request.ContentType = "application/x-www-form-urlencoded;";
                                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                                Stream myResponseStream = response.GetResponseStream();
                                MemoryStream stmMemory = new MemoryStream();
                                byte[] buffer = new byte[64 * 1024];
                                int y;
                                while ((y = myResponseStream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    stmMemory.Write(buffer, 0, y);
                                }
                                arraryByte = stmMemory.ToArray();
                                stmMemory.Close();
                                myResponseStream.Close();
                            }                           
                            Dictionary<string, object> postParams = new Dictionary<string, object>();
                            postParams.Add("orderId", 1);
                            postParams.Add("handleId", 2);
                            postParams.Add("accountName", 3);                            
                            string urlfile = getIP + "/subcenter/orderFile/uploadFiles";
                            string Authorizationfile = Gereral.newservice.GetAuthorization();
                            newservice.PostFiles(urlfile, postParams, strFileName, filePath, Authorizationfile, arraryByte);

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雷东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值