<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <!DOCTYPE html> <html> <head runat="server"> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script type="text/javascript"> function SaveAs() { var imgURL = document.getElementById("image").src; window.location.href = '/Home/SaveAs?url=' + imgURL; } </script> </head> <body> <div> <img id="image" src="../../Images/Koala.jpg" width="100px;" height="100px;" alt=""/><br /> <input onclick="SaveAs()" value="下载" type="button"/> </div> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Net; using System.IO; namespace DownLoadPic.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } public void SaveAs(string url) { WebClient my = new WebClient(); byte[] mybyte; var len = url.Split(new char[] { '/' }).Length; var image_name = url.Split(new char[] { '/' })[len - 1]; mybyte = my.DownloadData(url); MemoryStream ms = new MemoryStream(mybyte); System.Drawing.Image img; img = System.Drawing.Image.FromStream(ms); img.Save("C:\\Users\\DELL\\Downloads\\" + image_name + ""); //保存 Server.MapPath("/") OpenorSaveEPPlus("C:\\Users\\DELL\\Downloads\\" + image_name, image_name); /*服务器存一个,浏览器存一个*/ } public void OpenorSaveEPPlus(string outFile, string fileName) { ContentResult vResult = new ContentResult(); FileInfo info = new FileInfo(outFile); long size = 0; if (info.Exists) size = info.Length; this.Response.AddHeader("content-type", "application/x-msdownload;"); this.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName)); this.Response.AddHeader("content-length", size.ToString()); this.Response.WriteFile(outFile, 0, size); } } }
原文链接
从MSDN中我们可以得知,WebClient的作用就是“Provides common methods for sending data to and receiving data from a resource identified by a URI.”也就是说我们可以通过这个类去访问与获取网络上的资源文件。
WebClient client = new WebClient(); //第一种 string URLAddress = @"http://files.cnblogs.com/x4646/tree.zip"; string receivePath=@"C:\"; client.DownloadFile(URLAddress, receivePath + System.IO.Path.GetFileName(URLAddress)); //就OK了。 //第二种 Stream str = client.OpenRead(URLAddress); StreamReader reader = new StreamReader(str); byte[] mbyte = new byte[1000000]; int allmybyte = (int)mbyte.Length; int startmbyte = 0; while (allmybyte > 0) { int m = str.Read(mbyte, startmbyte, allmybyte); if (m == 0) break; startmbyte += m; allmybyte -= m; } reader.Dispose(); str.Dispose(); string path = receivePath + System.IO.Path.GetFileName(URLAddress); FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); fstr.Write(mbyte, 0, startmbyte); fstr.Flush(); fstr.Close();