首页 新闻 搜索 专区 学院

C#模拟表单上传文件及参数时报错

0
悬赏园豆:200 [已解决问题] 解决于 2021-05-07 10:54

string serviceUrl = string.Format("http://" + IP + "/api/wj.kc?act=UploadFile");
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);

        string filePath = @"C://Shot//Manual.jpg";
        string fileName = "Manual.jpg";

        if (File.Exists(filePath))
        {

            byte[] fileContentByte = new byte[1024]; // 文件内容二进制

            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            fileContentByte = new byte[fs.Length]; // 二进制文件
            fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            dynamic s =
            new
            {
                parms =
                new
                {
                    s_yonghuh = yonghuh,
                    i_year = year
                }
            };
            string json = JsonConvert.SerializeObject(s);

            var buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(json);

            string boundary = "----" + DateTime.Now.Ticks.ToString("x");
            string Enter = "\r\n";

            string modelIdStr = "--" + boundary + Enter
                    + "Content-Disposition: form-data; name=\"parms\"" + Enter + Enter
                    + json + Enter;

            string fileContentStr = "--" + boundary + Enter
                    + "Content-Type:image/jpeg" + Enter
                    + "Content-Disposition: form-data; name=\"fileContent\"; filename=\"" + fileName + "\"" + Enter + Enter;
            
            myRequest.Method = "POST";
            myRequest.Timeout = 70000;
            myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            myRequest.KeepAlive = true;
            myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            myRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
           
            Stream myRequestStream = myRequest.GetRequestStream();

            var modelIdStrByte = Encoding.UTF8.GetBytes(modelIdStr);//modelId所有字符串二进制

            var fileContentStrByte = Encoding.UTF8.GetBytes(fileContentStr);//fileContent一些名称等信息的二进制(不包含文件本身)

            myRequestStream.Write(modelIdStrByte, 0, modelIdStrByte.Length);

            myRequestStream.Write(fileContentStrByte, 0, fileContentStrByte.Length);

            myRequestStream.Write(fileContentByte, 0, fileContentByte.Length);

            // 获取接口返回值
            // 通过Web访问对象获取响应内容
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            reader.Close();
            myResponse.Close();
BengBaLaHei的主页 BengBaLaHei | 初学一级 | 园豆:35
提问于:2021-05-06 10:06
< >
分享
最佳答案
0

下面是我的代码(根据业务,你自己调整一下)

 internal class UploadHelper
    {
        public static string PostDataFile(UploadInfo info)
        {
            #region

            if (info == null) throw new ArgumentNullException(nameof(info));
            if (string.IsNullOrEmpty(info.ComparyId)) throw new ArgumentNullException(info.ComparyId);
            if (string.IsNullOrEmpty(info.UploadType)) throw new ArgumentNullException(info.UploadType);
            if (string.IsNullOrEmpty(info.TokenKey)) throw new ArgumentNullException(info.TokenKey);
            if (string.IsNullOrEmpty(info.FileName)) throw new ArgumentNullException(info.FileName);
            int tmpInt;
            if (!int.TryParse(info.ComparyId, out tmpInt)) throw new InvalidCastException(info.FileName);
            if (!int.TryParse(info.UploadType, out tmpInt)) throw new InvalidCastException(info.UploadType);
            if (info.Bytes == null || info.Bytes.Length < 1) throw new ArgumentException("info.Bytes");

            #endregion

            #region build Boundary

            var tmpGuid = Guid.NewGuid();
            var strBoundary = "--" + tmpGuid;
            var strbtyes = Encoding.UTF8.GetBytes("\r\n" + strBoundary + "--\r\n");
            var sb = new StringBuilder();
            //第一个参数(companyID)
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Type: text/plain; charset=utf-8");
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=companyID");
            sb.Append("\r\n\r\n");
            sb.Append(info.ComparyId);
            sb.Append("\r\n");
            //第二个参数(uploadType)
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Type: text/plain; charset=utf-8");
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=uploadType");
            sb.Append("\r\n\r\n");
            sb.Append(info.UploadType);
            sb.Append("\r\n");
            //第三个参数(tokenKey)
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Type: text/plain; charset=utf-8");
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=tokenKey");
            sb.Append("\r\n\r\n");
            sb.Append(info.TokenKey);
            sb.Append("\r\n");
            //第四个参数(文件信息)
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=attachment; filename=\"" + info.FileName + "\"");
            sb.Append("\r\n\r\n");

            #endregion

            var headerBytes = Encoding.UTF8.GetBytes(sb.ToString());
            var request = (HttpWebRequest) WebRequest.Create(info.url);
            request.ContentType = "multipart/form-data; boundary=\"" + tmpGuid + "\"";
            request.Method = "POST";
            request.AllowWriteStreamBuffering = false;
            request.KeepAlive = true;
            request.Timeout = 1000*60*5;
            request.ServicePoint.Expect100Continue = true;
            request.ContentLength = headerBytes.Length + info.Bytes.Length + strbtyes.Length;
            using (var stream = request.GetRequestStream())
            {
                stream.Write(headerBytes, 0, headerBytes.Length);
                stream.Write(info.Bytes, 0, info.Bytes.Length);
                stream.Write(strbtyes, 0, strbtyes.Length);
                using (var oWResponse = request.GetResponse())
                    using (var s = oWResponse.GetResponseStream())
                    {
                        if (s == null) throw new ArgumentNullException(info.ComparyId);
                        return (new StreamReader(s)).ReadToEnd();
                    }
            }
        }
    }

    public sealed class UploadInfo
    {
        public Uri url { get; set; }
        public string FileName { get; set; }
        public string ComparyId { get; set; }
        public string UploadType { get; set; }
        public string TokenKey { get; set; }
        public byte[] Bytes { get; set; }
    }
收获园豆:200
server126 | 菜鸟二级 |园豆:241 | 2021-05-06 10:41
其他回答(2)
0

HttpWebRequest 没怎么用过,一般都是用HttpClient

diudiu1 | 园豆:710 (小虾三级) | 2021-05-06 10:18
0

接口框架有修改导致报错

BengBaLaHei | 园豆:35 (初学一级) | 2021-05-07 09:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册