質問

I am saving a wav and an mp3 file to google cloud storage (rather than blobstore) as per the instructions. However, in doing so the MIME type of the file is lost and instead it is converted to binary/octet-stream which unfortunately breaks the apps I'm working with.

  1. How can I set the MIME type upon writing the file?

  2. Is there a way to set the MIME type automatically based on the file i.e. if it's an mp3 file it gets saved as audio/mpeg and if wav its audio/wav?

役に立ちましたか?

解決

Here is an example:

def gcs_write_blob(dyn, blob):
    """ update google cloud storage dyn entity """

    gcs_file_name = '/%s/%s' % (default_bucket, dyn.filename)

    content_type = mimetypes.guess_type(dyn.filename)[0]
    if dyn.extension in ['js', 'css']:
        content_type += b'; charset=utf-8'

    with gcs.open(gcs_file_name, 'w', content_type=content_type,
                  options={b'x-goog-acl': b'public-read'}) as f:
        f.write(blob)

    return gcs_file_name

Taken from this gist: https://gist.github.com/voscausa/9541133

他のヒント

The BlobInfo class has a "content_type" field that you can use to set the mime type of the object.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top