원격 서버 자원의 MIME 유형을 포함하는 Content-Type
헤더를 전송한다. 예를 들면 다음과 같습니다.
Content-Type: image/png
따라서이 헤더의 값을 검토하고 파일에 대한 적절한 확장자를 선택할 수 있습니다. 예를 들어 당신이 URL에서 확장을 추출 할 경우
WebRequest request = WebRequest.Create("http://0.gravatar.com/avatar/a5a5ed70fa7c651aa5ec9ca8de57a4b8?s=60&d=identicon&r=G");
using (WebResponse response = request.GetResponse())
using (Stream stream = response.GetResponseStream())
{
string contentType = response.ContentType;
// TODO: examine the content type and decide how to name your file
string filename = "test.jpg";
// Download the file
using (Stream file = File.OpenWrite(filename))
{
// Remark: if the file is very big read it in chunks
// to avoid loading it into memory
byte[] buffer = new byte[response.ContentLength];
stream.Read(buffer, 0, buffer.Length);
file.Write(buffer, 0, buffer.Length);
}
}
웹 요청을 보낼 때 Content-Type을 얻는 방법. –
할 수 없습니다. 결국, 실제로 서버가 전송할 때까지 서버가 귀하에게 보낼 것을 어떻게 예상 할 수 있습니까? 일단 WebResponse가 있으면 해당 content-type을 얻을 수 있습니다. – spender
@Abhishek Bhalani의 Content-Type 헤더는 요청이 아니라 응답에 있습니다. 나는 그 모범을 보여 주었다. –