将在线文件,保存到自己服务器
实现思路: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; }