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


     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("
    --" + boundary + "
    ");//开始边界符
                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}"
    
    {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("
    --" + boundary + "--
    ");
    
                for (int k = 0, k2 = files.Length; k < k2; k++)
                {
                    string fname = paramFileName;
                    string headerTemplate = "Content-Disposition: form-data; name="{0}"; filename="{1}"
    Content-Type: {2}
    
    ";
                    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;
            }
  • 相关阅读:
    定时任务 常用cron表达式
    链接UTF-8编码带BOM尾,访问出现404
    centos安装nginx
    cnetos安装jdk
    javaweb数据分页
    mvn clean install对idea中项目结构的影响
    spring使用servlet过滤器filter,进行登录校验
    docker安装mysql并修改远程登陆权限
    使用token令牌控制接口幂等性
    718.最长重复子数组
  • 原文地址:https://www.cnblogs.com/codehistory/p/13846994.html
Copyright © 2020-2023  润新知