其他分享
首页 > 其他分享> > s3存储桶中的utf-8文件名

s3存储桶中的utf-8文件名

作者:互联网

是否可以使用utf-8编码名称(例如“åøæ.jpg”)向s3添加密钥?

使用boto上传时出现以下错误:

<Error><Code>InvalidURI</Code><Message>Couldn't parse the specified URI.</Message>

解决方法:

@ 2083:这是一个古老的问题,但是如果您还没有找到解决方案,那么对于像我这样来到这里的其他所有人,我都在寻找答案:

从官方文档(http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html):

Although you can use any UTF-8 characters in an object key name, the
following key naming best practices help ensure maximum compatibility
with other applications. Each application may parse special
characters differently. The following guidelines help you maximize
compliance with DNS, web safe characters, XML parsers, and other APIs.

Safe Characters

The following character sets are generally safe for use in key names:

Alphanumeric characters [0-9a-zA-Z]

Special characters !, -, _, ., *, ‘, (, and )

The following are examples of valid object key names:

4my-organization

my.great_photos-2014/jan/myvacation.jpg

videos/2014/birthday/video1.wmv

但是,如果像我一样,您真正想要的是允许UTF-8字符的文件名(请注意,它可以与键名不同).您有办法做到!

http://www.bennadel.com/blog/2591-embedding-foreign-characters-in-your-content-disposition-filename-header.htmhttp://www.bennadel.com/blog/2696-overriding-content-type-and-content-disposition-headers-in-amazon-s3-pre-signed-urls.htm(向Ben Nadal致敬),您可以通过确保下载文件时S3覆盖Content-Disposition标头来实现.

正如我在Java中所做的那样,我在此处包括了代码,我相信您将能够轻松将其转换为Python :):

      AmazonS3 s3 = S3Controller.getS3Client();

        //as per http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html

        String key = fileName.substring(fileName.indexOf("-")).replaceAll("[^a-zA-Z0-9._]", "");
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                S3Controller.bucketNameForBucket(S3Controller.Bucket.EXPORT_BUCKET), 
                key,
                file);
        // we can always regenerate these files, so we can used reduced redundancy storage
        putObjectRequest.setStorageClass(StorageClass.Standard);
        String urlEncodedUTF8Filename = key;
        try {
            //http://www.bennadel.com/blog/2696-overriding-content-type-and-content-disposition-headers-in-amazon-s3-pre-signed-urls.htm
            //http://www.bennadel.com/blog/2591-embedding-foreign-characters-in-your-content-disposition-filename-header.htm
            //Issue#179
            urlEncodedUTF8Filename = URLEncoder.encode(fileName.substring(fileName.indexOf("-")), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            LOG.warn("Could not URLEncode a filename. Original Filename: " + fileName, e );
        }

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentDisposition("attachment; filename=\"" + key + "\"; filename*=UTF-8''"+ urlEncodedUTF8Filename);
        putObjectRequest.setMetadata(metadata);

        s3.putObject(putObjectRequest);

它应该帮助:)

标签:amazon-s3,boto,python
来源: https://codeday.me/bug/20191122/2058337.html