Skip to content
Console

Auto-detect MIME types on upload

Use Bitiful S4 to detect the MIME type of file objects automatically

In 2024, we strengthened detection of the M2TS and M4S video segment types to help you deal with increasingly serious resource abuse attacks.

In the best practice Upload files securely from the client, the JavaScript example at the end deliberately removes Content-Type, because:

  • Some HTTP libraries (such as axios) send application/x-www-form-urlencoded by default with PUT requests, and that gets saved as the object's type;
  • In the S3 protocol, if you send the file's MIME type as Content-Type when uploading, it is saved as metadata in the S3 backend (telling S3 which MIME type the uploaded object is)

So the best approach may be to set Content-Type to the MIME type of the uploaded file, for example:

                const config = {
                    headers: {
                        'Content-Type': 'image/jpeg',
                    },
                };

On AWS / OSS, the best approach may then be to write JavaScript that determines the file type reliably, and tell the server which MIME type of file we are about to upload when requesting the presigned link:

        const url = `/s3_upload_url`;
        const params = {key: '1.jpg', mime: 'image/jpeg'};

On Bitiful S4, we have a better option:

When Bitiful S4 receives an upload request with an empty Content-Type, it automatically and intelligently determines the file's MIME type from the extension and the bytes.

On AWS S3 and OSS, they all become "application/octet-stream"

Unlike file.type in JavaScript, which relies only on the extension, leaving MIME detection to S4 is more reliable and accurate.

All you need to do is:

  1. Delete your MIME detection code
  2. Set Content-Type to null when you send the Put request

How to write it for each upload method

MethodHow
Browser fetch, XMLHttpRequestSend file.slice(0, file.size, "") to remove the type inferred by the browser
axiosSet the request header "Content-Type": null
SDKs in each languageDo not set ContentType. Some SDKs fill it in automatically from the extension or a default, so go by the actual type after uploading
curlAdd -H "Content-Type:"

If a presigned link specified ContentType when it was signed, you must send the same value and cannot use auto-detection.

Verify the result

curl -I "https://my-bucket.s3.bitiful.net/images/photo.jpg"

You can also hover over a file icon in File Management (文件管理) in the console to see its Content-Type. See Manage files.