【问题标题】:FileWebRequest Not Returning Proper MIME for Local FileFileWebRequest 没有为本地文件返回正确的 MIME
【发布时间】: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 是否设置好?
  • 由于代码格式问题,我正在更新问题。

标签: c# .net .net-4.0


【解决方案1】:

我做了一些额外的研究......显然这是微软正在植入的硬编码缺陷。

Here is the MSDN Article 描述 FileWebResponse.GetContentType 总是返回 binary/octet-stream,然后进一步解释为 Application/Octet-Stream。

【讨论】:

    猜你喜欢
    • 2016-12-30
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    相关资源
    最近更新 更多