单击 preSignedRequest 链接时,AWS S3 强制下载文件

Lar*_*una 2 php amazon-s3 amazon-web-services

我正在使用 AWS S3 生成文件的 createPresignedRequest() 。当用户单击在新窗口中打开的链接时,我希望它强制下载。我可以做些什么来启用此功能吗?我已经查看了文档,但没有看到我需要的东西。

这是我创建 url 的代码:

 $s3 = new S3Client([
      'credentials'=>[
           'key'=>$key,
           'secret'=>$secret,
      ],
      'region'=>'us-west-2',
      'version'=>'2006-03-01',
 ]);
 $cmd = $s3->getCommand('GetObject', [
      'Bucket' => $buckname,
      'Key'    => $file,
 ]);
 $request = $s3->createPresignedRequest($cmd, '+7 days');
 $secureUrl = (string) $request->getUri();
 echo $secureUrl; // When the user clicks on the link - how can I force download the file instead of open in a new window.
Run Code Online (Sandbox Code Playgroud)

Mic*_*bot 5

您可以在生成预签名 URL 时通过添加参数来强制ResponseContentDisposition下载GetObject

'ResponseContentDisposition' => '<string>',
Run Code Online (Sandbox Code Playgroud)

这会指示 S3 设置一个响应标头,其值为使用签名 URL 时Content-Disposition的值。<string>对象保持不变。

要使用的值'<string>'可以是以下之一:

'attachment'
'attachment; filename="some-filename.jpg"'
Run Code Online (Sandbox Code Playgroud)

第二个示例将导致大多数浏览器使用您指定的名称保存文件,而不是其在 S3 中的名称。;after 这个词后面有一个空格attachment

当您执行此操作时,您会注意到签名的 URL 现在包含S3 API 参考&response-content-dispositon=...中提到的内容。

或者,您可以在将对象上传到 S3 时将 设定Content-Disposition为所需的值,这将自动出现在所有下载中。