从cdn URL下载图像文件

时间:2016-09-18 23:04:00

标签: c# asp.net .net c#-4.0

我正在尝试从Asp.net中的以下网址下载文件https://scontent-sit4-1.xx.fbcdn.net/v/t1.0-9/14333603_1289676231065862_2460190844802989442_n.jpg?oh=f6ccebc305e599e6dcc0bb7c994d8ac4&oe=586F4DD8 在img标签中将此url应用为src工作正常,但我需要将此图像保存在我的下载文件夹中。

我尝试了WebClient.Download方法,Downloaddata和webrequest方法,但是他们返回403禁止错误

1 个答案:

答案 0 :(得分:2)

尝试使用WebRequest,如下所示: (你必须相应地指定你的下载文件夹和链接)

string lnk = @"https://scontent-sit4-1.xx.fbcdn.net/v/t1.0-9/14333603_1289676231065862_2460190844802989442_n.jpg?oh=f6ccebc305e599e6dcc0bb7c994d8ac4&oe=586F4DD8";
WebRequest request = HttpWebRequest.Create(lnk);
((HttpWebRequest)request).AllowAutoRedirect = true;
((HttpWebRequest)request).UserAgent = @"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
int dataLength;
int bytesRead;
int wroteSoFar = 0;
var response = request.GetResponse();
Stream responseStream = response.GetResponseStream();

byte[] buffer = new byte[1024];
using (FileStream oFile = new FileStream(Path.Combine(Environment.CurrentDirectory, @"img.jpg"), FileMode.Append, FileAccess.Write))
{
    dataLength = (int)response.ContentLength;
    do
    {
        bytesRead = responseStream.Read(buffer, 0, buffer.Length);
        oFile.Write(buffer, 0, bytesRead);
        wroteSoFar += bytesRead;
        //Console.WriteLine($"{(wroteSoFar / 1000).ToString("N0")} KB / {(dataLength / 1000).ToString("N0")} KB");
    }
    while (bytesRead != 0);
}

我设法像这样下载了它。