• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#后台实现一次上传多个文件

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 string result="";   
 string urlUploadMultiFile = "http://127.0.0.1:8090/overload/uploaddata.action";//上传地址
 //赋值
 infoData.id="123";
 infoData.name= "张三";
 infoData.date= "2020-10-20 15:50:00";
string jsonParam = JsonConvert.SerializeObject(infoData); List<string> fileLst = new List<string>(); fileLst.Add("1.jpg"); fileLst.Add("2.jpg"); fileLst.Add("3.jpg"); fileLst.Add(z"4video.mp4"); string[] filesArray = fileLst.ToArray();//strArray=[str0,str1,str2]//转数组 //调用 if (UploadMultiFile(urlUploadMultiFile, jsonParam, filesArray, "application/octet-stream", "file") > 0) {       result="成功"; }

上传方法

      /// <summary>
        /// 多文件上传
        /// </summary>
        /// <param name="url">请求路径</param>
        /// <param name="jsonParam">数据</param>
        /// <param name="files">图片路径</param>
        /// <param name="contentType"></param>
        /// <param name="paramFileName">对应的图片字段</param>
        /// <returns></returns>
        public static int UploadMultiFile(string url, string jsonParam, string[] files, string contentType, string paramFileName)
        {
           int result = -1;
            if (files.Length <= 0) return result;

            Dictionary<string, string> nvc = new Dictionary<string, string>();
            nvc.Add("queryParam", jsonParam);
            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");//边界符
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");//开始边界符
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
            Stream rs = wr.GetRequestStream();
            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);//写入边界符
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);//写入数据
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);//写入边界符

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            for (int k = 0, k2 = files.Length; k < k2; k++)
            {
                string fname = paramFileName;
                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                string header = string.Format(headerTemplate, fname, files[k], contentType);//写入字符串
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                rs.Write(headerbytes, 0, headerbytes.Length);//写入文件

                FileStream fileStream = new FileStream(files[k], FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    rs.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();
                if (k < k2 - 1) rs.Write(boundarybytes, 0, boundarybytes.Length);
            }
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();
            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                JObject resultJson = (JObject)JsonConvert.DeserializeObject(reader2.ReadToEnd());
                if (resultJson.Property("message") != null && resultJson["message"].ToString() == "操作成功")
                {
                    result = 1;
                    SysCfg.WriteLog("result:" + resultJson, false);
                }
                //result = reader2.ReadToEnd();
            }
            catch (Exception ex)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
                SysCfg.WriteLog("UploadMultiFile,ex:" + ex.Message);
                result = -1;
            }
            finally
            {
                wr = null;
            }
            return result;
        }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#WinForm取消DataGridView的默认选中Cell使其不反蓝发布时间:2022-07-13
下一篇:
C/C++访问MySql数据库的示例代码发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap