你可以下载一个PDF这样
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = req.GetResponse();
//check the filetype returned
string contentType = response.ContentType;
if(contentType!=null)
{
splitString = contentType.Split(';');
fileType = splitString[0];
}
//see if its PDF
if(fileType!=null && fileType=="application/pdf"){
Stream stream = response.GetResponseStream();
//save it
using(FileStream fileStream = File.Create(fileFullPath)){
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}
}
response.Close();
事实上,它可能来自一个.aspx处理程序不实际的事情,它是哑剧在服务器响应时返回用过的。
如果您正在获取泛型MIME类型,如application/octet-stream,那么您必须使用更合理的方法。
假设您不能简单地使用文件扩展名(例如.aspx),则可以先将该文件复制到MemoryStream(请参阅How to get a MemoryStream from a Stream in .NET?)。一旦你有一个文件的内存流,你可以采取'厚脸皮'偷看它(我说厚颜无耻,因为它不是解析PDF文件的正确方法)
我不是PDF格式的专家,但我相信读第5个字符与ASCII阅读器将产生“%PDF-”,这样你就可以识别与
bool isPDF;
using( StreamReader srAsciiFromStream = new StreamReader(memoryStream,
System.Text.Encoding.ASCII)){
isPDF = srAsciiFromStream.ReadLine().StartsWith("%PDF-");
}
//set the memory stream back to the start so you can save the file
memoryStream.Position = 0;
应用程序/八位字节流的一些网址返回的MIME类型可以有什么样的文件。在这种情况下,我们如何检测pdf? – kamalpreet 2014-10-17 15:39:32
我已更新回答你的问题。 – 2014-10-17 17:28:03
我们如何使用Response.Write()将其作为Content Typr =“application/pdf”写在客户端的浏览器上? – kamalpreet 2014-10-18 15:31:10