【发布时间】:2014-01-16 20:56:46
【问题描述】:
所以这类似于问题发生的情况:FileWebRequest not returning what it should
我正在尝试使用 URI/WebRequest 下载文件,其想法是我们可以在 FTP/Web/Local 文件操作中使用该方法。
代码如下:
var req = WebRequest.Create(uri);
var fileExt = Path.GetExtension(uri.AbsolutePath).ToUpper().Substring(1);
switch (fileExt)
{
case "JPG":
case "JPEG":
req.ContentType = _mimeJpeg;
break;
case "PNG":
req.ContentType = _mimePng;
break;
case "TIF":
case "TIFF":
req.ContentType = _mimeTiff;
break;
}
req.Timeout = timeout;
//The GetResponse call actually makes the request
var resp = req.GetResponse();
//Check the content type of the response to make sure it is
//one of the formats we support
if (resp.ContentType != _mimeTiff)
{
var contentType = resp.ContentType;
resp.Close();
throw new Exception(String.Format("The image at the URL you provided is in an unsupported format ({0}). " + "Uploaded images must be in either JPEG, PNG, or TIFF formats.", contentType));
}
Microsoft 自己的文档说 Resp.ContentType 的 ContentType 始终是“binary\octet-stream”(找到 here)。问题是这会导致稍后出现问题,因为我们需要一个图像文件(我们尝试使用此方法加载的文件类型是 GIF、TIFF、JPEG 等)。我们应该怎么做?
编辑
具体错误发生在:
//Check the content type of the response to make sure it is
//one of the formats we support
if (resp.ContentType != _mimeTiff)
{
var contentType = resp.ContentType;
resp.Close();
throw new Exception(String.Format("The image at the URL you provided is in an unsupported format ({0}). " + "Uploaded images must be in either JPEG, PNG, or TIFF formats.", contentType));
}
因为我们一直在获取 MIME 类型的 Application/Octet-Stream。
【问题讨论】:
-
哪个部分不工作?
req.ContentType是否设置好? -
由于代码格式问题,我正在更新问题。