• C# 将http在线文件,保存到服务器指定位置


    将在线文件,保存到自己服务器

    实现思路:1、HttpWebRequest请求该文件,获取流文件。

          2、然后流转为byte[]

          3、使用File类的WriteAllBytes ,将byte[] 写入文件

       [HttpPost]
            public JsonResult UploadHtppFile(string url)
            {
                try
                {
                    //可以是任意文件
                    url = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1906469856,4113625838&fm=26&gp=0.jpg";
    
                    //发起请求,读取流,转为byte[]
                    var bytes = Url_To_Byte(url);
                    //名称尽量不要重复,因为名称重复WriteAllBytes会覆盖之前的
                    var fileName = DateTime.Now.ToString("yyyyMMddHHmmssms") + ".jpg";
                    var filePath = "upload/" + fileName;
                    //文件保存到该路径下
                    System.IO.File.WriteAllBytes(Server.MapPath("~/" + filePath), bytes);
    
                    return Json(new { code = 0, hint = "保存成功", file = filePath });
                }
                catch (Exception ex)
                {
                    return Json(new { code = 1, hint = "保存失败:" + ex.Message });
                    throw;
                }
            }
    
            /// <summary>
            /// http路径图片,转为byte[]
            /// </summary>
            /// <param name="imgUrl">图片路径</param>
            /// <returns></returns>
            public static byte[] Url_To_Byte(string imgUrl)
            {
                //创建HttpWebRequest对象,请求图片url
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);
    
                byte[] bytes;
                //获取流
                using (Stream stream = request.GetResponse().GetResponseStream())
                {
                    //保存为byte[]
                    using (MemoryStream mstream = new MemoryStream())
                    {
                        int count = 0;
                        byte[] buffer = new byte[1024];
                        int readNum = 0;
                        while ((readNum = stream.Read(buffer, 0, 1024)) > 0)
                        {
                            count = count + readNum;
                            mstream.Write(buffer, 0, readNum);
                        }
                        mstream.Position = 0;
                        using (BinaryReader br = new BinaryReader(mstream))
                        {
                            bytes = br.ReadBytes(count);
                        }
                    }
                }
                return bytes;
            }
    

      

  • 相关阅读:
    P1828 [USACO3.2]香甜的黄油 Sweet Butter 题解
    P2058 海港 题解
    浅谈三分算法
    海伦公式的证明
    一年一回首
    再谈单调队列优化 & 背包九讲
    浅谈单调队列
    P1440 求m区间内的最小值 题解
    CF1374B Multiply by 2, divide by 6 题解
    组合数、杨辉三角与递推算法
  • 原文地址:https://www.cnblogs.com/liuzheng0612/p/13020918.html
Copyright © 2020-2023  润新知