s3 bu中的utf8文件名

2024-10-01 09:26:50 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以为s3添加一个utf-8编码的密钥,如“åæ.jpg”?在

我在使用boto上载时遇到以下错误:

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

Tags: themessage编码s3parse错误密钥code
2条回答

来自AWS常见问题: 密钥是一个Unicode字符序列,其UTF-8编码长度最多为1024字节。在

根据我的经验,使用ASCII。在

@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将覆盖内容处理头。在

正如我在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);

它应该有帮助:)

相关问题 更多 >