I upload files to S3 successfully with my application. I do a direct upload from the browser using a signedUrl that my server generates for me using the aws-sdk v3.
To get the singed URL it looks a bit like this
const s3Params = {
Bucket : bucketName,
Key : fileName,
ContentType:fileType,
// Metadata:{'Content-Disposition':'attachment'}
// ContentDisposition:'attachment'
};
try {
const command = new PutObjectCommand(s3Params);
const url = await getSignedUrl(s3v3,command,{expiresIn:60});
return url;
} catch (e) {
console.log('************** there was an error signing th url');
console.log(e);
throw e;
}
};
This is working perfectly fine, but then as i read a bit of the documentation I saw that i should be able to set the header ContentDisposition. In this documentation it says that the input of PutObjectCommand extends from the PutObjectRequest
The latter has an optional parameter called ContentDisposition
as i would like to set this to attachment, to allow me to prompt a "download" window for my users. However, when I use the signedURL as above but add the ContentDisposition:'attachment'
field i get a Forbidden Error.
Does anyone know if im missing anything here? is this not an actual option or do i need to modify something in my permissions of S3 for this?
CodePudding user response:
We have to specify the ContentDisposition
for the PutObjectCommand
param and also for the getSignedUrl
function as such:
async function main(fileName, bucketName, fileType) {
const s3Params = {
Bucket: bucketName,
Key: fileName,
ContentType: fileType,
ContentDisposition: 'attachment'
};
const client = new S3Client({region: 'us-east-1'});
const command = new PutObjectCommand(s3Params);
const url = await getSignedUrl(client, command, {expiresIn: 60, ContentDisposition: 'attachment'});
const file = await fs.readFile(fileName);
const result = await axios({
method: 'put',
url,
data: file,
headers: {
'Content-Type': fileType,
'Content-Disposition': 'attachment'
}
});
return result;
}