我有一个图像的网址。例如“http://testsite.com/web/abc.jpg”。我想在我的本地文件夹中的“c:\ images \”中复制该URL。并且当我将该文件复制到文件夹时,我必须将图像重命名为“c:\ images \ xyz.jpg”。将图像文件从web url复制到本地文件夹?
我们该怎么做?
我有一个图像的网址。例如“http://testsite.com/web/abc.jpg”。我想在我的本地文件夹中的“c:\ images \”中复制该URL。并且当我将该文件复制到文件夹时,我必须将图像重命名为“c:\ images \ xyz.jpg”。将图像文件从web url复制到本地文件夹?
我们该怎么做?
请求图像并保存。例如:
byte[] data;
using (WebClient client = new WebClient()) {
data = client.DownloadData("http://testsite.com/web/abc.jpg");
}
File.WriteAllBytes(@"c:\images\xyz.jpg", data);
你可以使用一个WebClient
:
using (WebClient wc = new WebClient())
wc.DownloadFile("http://testsite.com/web/abc.jpg", @"c:\images\xyz.jpg");
这是假设你确实有写权限的文件夹C:\images
。
远程服务器返回错误:(401)未经授权。 – James123 2011-04-28 21:03:28
用一个您有权从其下载的URL来尝试它,否则您需要向WebClient提供在目标服务器上工作的凭据。 – BrokenGlass 2011-04-28 21:09:19
这不是太困难。打开Web客户端和抢位,保存在本地....
using (WebClient webClient = new WebClient())
{
using (Stream stream = webClient.OpenRead(imgeUri))
{
using (Bitmap bitmap = new Bitmap(stream))
{
stream.Flush();
stream.Close();
bitmap.Save(saveto);
}
}
}
你为什么要强制JPG图片变成位图? – 2014-01-10 15:38:59
string path = "~/image/";
string picture = "Your picture name with extention";
path = Path.Combine(Server.MapPath(path), picture);
using (WebClient wc = new WebClient())
{
wc.DownloadFile("http://testsite.com/web/abc.jpg", path);
}
其作品对我来说
远程服务器返回错误:(401)未经授权。 – James123 2011-04-28 21:03:10
我喜欢这个答案,而不是直接使用DownloadFile,因为它提供了将数据提交到文件之前比较数据的机会。 – MikeDub 2016-11-18 21:18:14