zoukankan      html  css  js  c++  java
  • 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;
            }
    

      

  • 相关阅读:
    最大子数组问题:股票
    dfs小练 【dfs】
    java小知识点简单回顾
    cdoj841-休生伤杜景死惊开 (逆序数变形)【线段树 树状数组】
    二路归并排序算法
    优秀Python学习资源收集汇总(强烈推荐)
    怎么学习逆向工程?
    __cdecl 、__fastcall、__stdcall
    getchar()、putchar()、gets()、puts()、cin.get()、cin.getline()、getline()
    <cctype>库
  • 原文地址:https://www.cnblogs.com/liuzheng0612/p/13020918.html
Copyright © 2011-2022 走看看