How to change file content type of AWS s3 bucket before uploading in PHP
P粉739706089
2023-09-02 15:55:35
<p>I have the following code that allows me to successfully upload files to my S3 bucket. </p>
<pre class="brush:php;toolbar:false;">$keyName = 'test_example/' . basename($_FILES["fileToUpload"]['tmp_name']);
$pathInS3 = 'https://s3.eu-west-2.amazonaws.com/' . $bucketName . '/' . $keyName;
//Add it to S3
try {
$s3->putObject(
array(
'Bucket'=>$bucketName,
'Key' => $keyName,
'contentType' => 'image/png',
'SourceFile' => $keyName,
'StorageClass' => 'REDUCED_REDUNDANCY'
)
);
} catch (S3Exception $e) {
die('Error:' . $e->getMessage());
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}</pre>
<p>The problem is that they download instead of displaying the image. I've looked around and tried adding: 'contentType' => 'image/png' and this doesn't change anything. The file is still uploaded as a Value application/octet-stream rather than a Jpg image. Is there a way to change this? </p>
Well, for some reason.
'contentType' => 'picture/png',
doesn't work for me. Instead I used
'ContentType' => 'Text/Plain Text',
I can now view my images without downloading.