• c#http post请求处理文件


    1、通过读取路径将文件转为byte[]

        

      //将一个file文件转化为byte[]
            public static byte[] GetBytesFromUrl1(string url)
            {
                byte[] b;
                FileWebRequest myReq = (FileWebRequest)WebRequest.Create(url);
                WebResponse myResp = myReq.GetResponse();
                Stream stream = myResp.GetResponseStream();
                //int i;
                using (BinaryReader br = new BinaryReader(stream))
                {
                    b = br.ReadBytes(1000000);
                    br.Close();
                }
                myResp.Close();
                return b;
            }
        //通过Url地址将文件转成byte[]
            public static byte[] GetBytesFromUrl(string url)
            {
                byte[] b;
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
                WebResponse myResp = myReq.GetResponse();
                Stream stream = myResp.GetResponseStream();
                //int i;
                using (BinaryReader br = new BinaryReader(stream))
                {
                    b = br.ReadBytes(500000);
                    br.Close();
                }
                myResp.Close();
                return b;
            }

     2、通过接口传递图片文件方法

         

                
    请求代码:
    string filePath = @"F: eTestimage12.jpg"; byte[] bt = GetBytesFromUrl1(filePath); string str = Convert.ToBase64String(bt);

            StringBuilder sb = new StringBuilder();
            sb.Append("filename=" + HttpUtility.UrlEncode("as", Encoding.UTF8));
            sb.Append("&fileimg=" + HttpUtility.UrlEncode(str, Encoding.UTF8));

    string res = HttpHelper.httpPost("接口地址", sb.ToString());

    接口地址接收代码:
     string str = Request["fileimg"] ?? "";
    string filename = Request["filename"]??"";
    byte[] byt = Convert.FromBase64String(str);

              FileStream fs = new FileStream(@"D:xxwebaabimages" + filename + ".jpg", FileMode.Create);
              BinaryWriter bw = new BinaryWriter(fs);
              //开始写入
              bw.Write(byt, 0, byt.Length);
              //关闭流
              bw.Close();
              fs.Close();

                   然后可以出来byt图片文件了 
  • 相关阅读:
    「SOL」开关(LOJ)
    「SOL」星际迷航(LOJ)
    「NOTE」概率生成函数
    「SOL」谢特(LOJ)
    「SOL」重建计划(BZOJ)
    「SOL」Tug of War(洛谷)
    「SOL」同余方程(LOJ)
    「SOL」Bad Cryptography(Codeforces)
    「SOL」小A与两位神仙(洛谷)
    「SOL」Social Distance(AtCoder)
  • 原文地址:https://www.cnblogs.com/wenghan/p/13896167.html
Copyright © 2020-2023  润新知