I'm required to retrieve and save an image from a website to my local folder. The image type varies between .png, .jpg and .gif
I've tried using
string url = @"http://redsox.tcs.auckland.ac.nz/CSS/CSService.svc/";
string saveLoc = @"/project1/home_image";
using (var wc = new WebClient())
{
wc.DownloadFile(url, saveLoc);
}
but this saves the file 'home_image' in the folder without the extension. My question is how do you determine the extension? Is there a simple way to do this? Can one use the Content-Type of the HTTP request? If so, how do you do this?
If you want to use a WebClient
, then you have to extract the header information from WebClient.ResponseHeaders
. You'll have to store it as a byte array first, and then save the file after getting your file information.
string url = @"http://redsox.tcs.auckland.ac.nz/CSS/CSService.svc/";
string saveLoc = @"/project1/home_image";
using (WebClient wc = new WebClient())
{
byte[] fileBytes = wc.DownloadData(url);
string fileType = wc.ResponseHeaders[HttpResponseHeader.ContentType];
if (fileType != null)
{
switch (fileType)
{
case "image/jpeg":
saveloc += ".jpg";
break;
case "image/gif":
saveloc += ".gif";
break;
case "image/png":
saveloc += ".png";
break;
default:
break;
}
System.IO.File.WriteAllBytes(saveloc, fileBytes);
}
}
I like my extensions to be 3 letters long if they can.... personal preference. If it doesn't bother you, you can replace the entire switch
statement with:
saveloc += "." + fileType.Substring(fileType.IndexOf('/') + 1);
Makes the code a little neater.
Try something like this
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Your URL");
request.Method = "GET";
var response = request.GetResponse();
var contenttype = response.Headers["Content-Type"]; //Get the content type and extract the extension.
var stream = response.GetResponseStream();
Then save the stream
来源:https://stackoverflow.com/questions/18543518/using-a-webclient-to-save-an-image-with-the-appropriate-extension