由于某些原因,我的S3存储桶中的文件被强制下载,而不是内联显示,所以如果我复制一个图像链接并将其粘贴到地址栏中,然后导航到它,它会促使我的浏览器下载它。相反,我实际上必须点击“打开图像”才能进入URL。
有没有改变S3提供文件的方式的方法?
由于某些原因,我的S3存储桶中的文件被强制下载,而不是内联显示,所以如果我复制一个图像链接并将其粘贴到地址栏中,然后导航到它,它会促使我的浏览器下载它。相反,我实际上必须点击“打开图像”才能进入URL。
有没有改变S3提供文件的方式的方法?
$client->putObject(array(
'Bucket' => 'buckname',
'Key' => $destination,
'SourceFile' => $source,
'ContentType' =>'image/jpeg', //<-- this is what you need!
'ACL' => 'public-read'//<-- this makes it public so people can see it
));
若要将内容以内嵌的形式显示而非作为附件下载,您需要同时指定“Content Disposition”。
$client->putObject(array(
'Bucket' => 'buckname',
'Key' => $destination,
'SourceFile' => $source,
'ContentType' =>'image/jpeg', //<-- this is what you need!
'ContentDisposition' => 'inline; filename=filename.jpg', //<-- and this !
'ACL' => 'public-read'//<-- this makes it public so people can see it
));
如果你正在使用Python,你可以将ContentType设置如下
s3 = boto3.client('s3')
mimetype = 'image/jpeg' # you can programmatically get mimetype using the `mimetypes` module
s3.upload_file(
Filename=local_path,
Bucket=bucket,
Key=remote_path,
ExtraArgs={
"ContentType": mimetype
}
)
您也可以在aws cli中实现相同的功能。请注意*.jpeg
。请参阅s3文档。
aws s3 cp \
--exclude "*" \
--include "*.jpeg" \
--content-type="image/jpeg" \
--metadata-directive="REPLACE" \
--recursive \
--dryrun \
s3://<bucket>/<path>/ \
s3://<bucket>/<path>/
或者,如果您想逐个修改对象,则可以考虑使用s3api copy-object
aws s3api copy-object \
--content-type="image/jpeg" \
--metadata-directive="REPLACE" \
--copy-source "<bucket>/<key>" \
--bucket "<bucket>" \
--key "<key>" \
--acl public-read
const params = {
Bucket: 'bucket-name',
Body: file,
ACL: 'public-read',
ContentType: contentType,
ContentEncoding: 'base64',
ContentDisposition: 'attachment',
};
ContentType
中,就会打开文件而不是下载。
当上传各种扩展名的文件时,这实际上非常好用。
$s3->putObject(
[
'Bucket' => ..,
'Key' => ..,
'Body' => ..,
'ContentType' => '', <---
'ACL' => 'public-read',
]);
var params = {
Bucket: config.BUCKET_NAME,
Key: fileName,
ContentEncoding: 'base64',
ContentDisposition: 'inline',
ContentType: 'image/jpeg',
Body: buf
};
Content-type
属性上。我使用的是Spring Boot,在s3中的内容数据保存为application/octet-stream
而非例如image/jpeg
的值属性。因此,当我打开文件链接时,浏览器会下载该文件。Content-type
!对我而言真正有效的方法是在保存S3文件之前将ContentType
参数设置为image/png
。