Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top