Module: JPSClient::ContentType

Defined in:
lib/jpsclient/utils/content_type.rb

Overview

上传文件的 Content-Type 推导

S3 对象最终的 Content-Type 由两处决定:简单上传是 PUT 时发送的 header, 分片上传是 CreateMultipartUpload 的 contentType。两条链路统一走这里的映射, 避免所有对象都存成 application/octet-stream,导致浏览器无法内联预览图片/视频、 Android 无法识别 apk 安装包。

Constant Summary collapse

DEFAULT =

无法识别扩展名时的兜底类型

'application/octet-stream'.freeze
EXTENSION_MAP =

扩展名 → Content-Type .ipa / .exe 保持 application/octet-stream:这是安装包分发的惯例值, 换成其他类型对客户端没有收益

{
  '.zip'  => 'application/zip',
  '.apk'  => 'application/vnd.android.package-archive',
  '.ipa'  => DEFAULT,
  '.exe'  => DEFAULT,
  '.png'  => 'image/png',
  '.jpg'  => 'image/jpeg',
  '.jpeg' => 'image/jpeg',
  '.gif'  => 'image/gif',
  '.bmp'  => 'image/bmp',
  '.webp' => 'image/webp',
  '.mp4'  => 'video/mp4',
  '.mov'  => 'video/quicktime',
  '.avi'  => 'video/x-msvideo',
  '.mkv'  => 'video/x-matroska',
  '.webm' => 'video/webm'
}.freeze

Class Method Summary collapse

Class Method Details

.for_file(file_path) ⇒ String

根据文件扩展名推导 Content-Type

Parameters:

  • file_path (String)

    文件路径

Returns:

  • (String)

    Content-Type,无法识别时返回 DEFAULT



39
40
41
# File 'lib/jpsclient/utils/content_type.rb', line 39

def for_file(file_path)
  EXTENSION_MAP.fetch(::File.extname(file_path.to_s).downcase, DEFAULT)
end