How can I upload image to AWS S3 bucket using pre-signed URL?

I would like to upload my image to AWS S3 using a pre-signed url created from backend. So, the process is – after submitting a form from Angular application, I’ll send an API request to Node.js backend for creating a pre-signed url and response back to Angular application. Using the pre-signed url Angular application will send a http request to the pre-signed url along with an image file.

So, at first I created a S3 bucket by adding following CORS policy.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"PUT"
],
"AllowedOrigins": [
"http://localhost:4200"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 3000
}
]
</code>
<code>[ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "PUT" ], "AllowedOrigins": [ "http://localhost:4200" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ] </code>
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT"
        ],
        "AllowedOrigins": [
            "http://localhost:4200"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 3000
    }
]

Also, I created a IAM policy –

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PolicyName",
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetObject",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::<timezone>-<bucket_name >",
"arn:aws:s3:::<timezone>-<bucket_name >/*"
]
}
]
}
</code>
<code>{ "Version": "2012-10-17", "Statement": [ { "Sid": "PolicyName", "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:GetObject", "s3:PutObject" ], "Resource": [ "arn:aws:s3:::<timezone>-<bucket_name >", "arn:aws:s3:::<timezone>-<bucket_name >/*" ] } ] } </code>
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PolicyName",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::<timezone>-<bucket_name >",
                "arn:aws:s3:::<timezone>-<bucket_name >/*"
            ]
        }
    ]
}

Here is the Node.js code that create and send pre-signed upload url –

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>exports.getS3SignedUrl = async (req, res, next) => {
try {
const s3 = new S3({
apiVersion: '2006-03-01',
accessKeyId: process.env.AWS_ID,
secretAccessKey: process.env.AWS_SECRET,
signatureVersion: 'v4',
region: process.env.AWS_REGION
});
const ext = req.query.fileType ? (req.query.fileType).split('/')[1] : null;
if (ext) {
const Key = `${randomUUID()}.${ext}`;
const s3Params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key,
Expires: 60 * 60,
ContentType: `image/${ext}`
}
const uploadUrl = await s3.getSignedUrl('putObject', s3Params);
return res.status(200).json({
uploadUrl,
Key
});
} else {
return res.status(404).json({
message: 'File not found'
});
}
} catch (error) {
console.log(error);
res.status(500).json({ "error": error });
}
}
</code>
<code>exports.getS3SignedUrl = async (req, res, next) => { try { const s3 = new S3({ apiVersion: '2006-03-01', accessKeyId: process.env.AWS_ID, secretAccessKey: process.env.AWS_SECRET, signatureVersion: 'v4', region: process.env.AWS_REGION }); const ext = req.query.fileType ? (req.query.fileType).split('/')[1] : null; if (ext) { const Key = `${randomUUID()}.${ext}`; const s3Params = { Bucket: process.env.AWS_BUCKET_NAME, Key, Expires: 60 * 60, ContentType: `image/${ext}` } const uploadUrl = await s3.getSignedUrl('putObject', s3Params); return res.status(200).json({ uploadUrl, Key }); } else { return res.status(404).json({ message: 'File not found' }); } } catch (error) { console.log(error); res.status(500).json({ "error": error }); } } </code>
exports.getS3SignedUrl = async (req, res, next) => {
    try {
        const s3 = new S3({
            apiVersion: '2006-03-01',
            accessKeyId: process.env.AWS_ID,
            secretAccessKey: process.env.AWS_SECRET,
            signatureVersion: 'v4',
            region: process.env.AWS_REGION
        });

        const ext = req.query.fileType ? (req.query.fileType).split('/')[1] : null;

        if (ext) {
            const Key = `${randomUUID()}.${ext}`;

            const s3Params = {
                Bucket: process.env.AWS_BUCKET_NAME,
                Key,
                Expires: 60 * 60,
                ContentType: `image/${ext}`
            }
            const uploadUrl = await s3.getSignedUrl('putObject', s3Params);
            
            return res.status(200).json({
                uploadUrl,
                Key
            });
        } else {
            return res.status(404).json({
                message: 'File not found'
            });
        }
    } catch (error) {
        console.log(error);
        res.status(500).json({ "error": error });
    }
}

Node.js code can create a pre-signed url and send it to Angular frontend. But the issue I am facing with uploading the file to AWS S3. When I execute a http request to the pre-signed url, it returns back a 400 bad request.

Here is the frontend code –

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> .......
const s3BucketUploadInformation = await
this.getS3SignedUrl(file);
await this.saveFileToS3Bucket(s3BucketUploadInformation.uploadUrl,
file);
.......
// We would not upload files to AWS S3 from the backend, instead of we would ask
// backend to create a AWS signed URL, later from the front end upload the file to
// S3 bucket.
public async saveFileToS3Bucket(uploadUrl: string, file: File) {
const headers = new HttpHeaders({ 'Content-Type': file.type });
const req = new HttpRequest('PUT', uploadUrl, file, { headers: headers, reportProgress: true })
let promise = new Promise((resolve, reject) => {
this.http.request(req)
.toPromise()
.then(
res => { // Success
resolve(res);
},
msg => { // Error
reject(msg);
}
);
});
return promise;
}
// Get AWS S3 signed url from backend.
public getS3SignedUrl(file: File) {
let promise = new Promise((resolve, reject) => {
const fileType: string = encodeURIComponent(file.type);
let apiURL = `${environment.API_ADMIN_URL}content/get-s3-signed-url?fileType=${fileType}`;
// Send API request to get AWS S3 signed URL, and an unique key from backend.
this.http.get(apiURL)
.toPromise()
.then(
res => { // Success
resolve(res);
},
msg => { // Error
reject(msg);
}
);
});
return promise;
}
</code>
<code> ....... const s3BucketUploadInformation = await this.getS3SignedUrl(file); await this.saveFileToS3Bucket(s3BucketUploadInformation.uploadUrl, file); ....... // We would not upload files to AWS S3 from the backend, instead of we would ask // backend to create a AWS signed URL, later from the front end upload the file to // S3 bucket. public async saveFileToS3Bucket(uploadUrl: string, file: File) { const headers = new HttpHeaders({ 'Content-Type': file.type }); const req = new HttpRequest('PUT', uploadUrl, file, { headers: headers, reportProgress: true }) let promise = new Promise((resolve, reject) => { this.http.request(req) .toPromise() .then( res => { // Success resolve(res); }, msg => { // Error reject(msg); } ); }); return promise; } // Get AWS S3 signed url from backend. public getS3SignedUrl(file: File) { let promise = new Promise((resolve, reject) => { const fileType: string = encodeURIComponent(file.type); let apiURL = `${environment.API_ADMIN_URL}content/get-s3-signed-url?fileType=${fileType}`; // Send API request to get AWS S3 signed URL, and an unique key from backend. this.http.get(apiURL) .toPromise() .then( res => { // Success resolve(res); }, msg => { // Error reject(msg); } ); }); return promise; } </code>
  .......
  const s3BucketUploadInformation = await 
     this.getS3SignedUrl(file);
  await this.saveFileToS3Bucket(s3BucketUploadInformation.uploadUrl, 
     file);
  .......

  // We would not upload files to AWS S3 from the backend, instead of we would ask 
  // backend to create a AWS signed URL, later from the front end upload the file to 
  // S3 bucket.
  public async saveFileToS3Bucket(uploadUrl: string, file: File) {
    const headers = new HttpHeaders({ 'Content-Type': file.type });
    const req = new HttpRequest('PUT', uploadUrl, file, { headers: headers, reportProgress: true })
    let promise = new Promise((resolve, reject) => {
      this.http.request(req)
        .toPromise()
        .then(
          res => { // Success
            resolve(res);
          },
          msg => { // Error
            reject(msg);
          }
        );
    });
    return promise;
  }

  // Get AWS S3 signed url from backend.
  public getS3SignedUrl(file: File) {
    let promise = new Promise((resolve, reject) => {
      const fileType: string = encodeURIComponent(file.type);
      let apiURL = `${environment.API_ADMIN_URL}content/get-s3-signed-url?fileType=${fileType}`;
      // Send API request to get AWS S3 signed URL, and an unique key from backend.
      this.http.get(apiURL)
        .toPromise()
        .then(
          res => { // Success
            resolve(res);
          },
          msg => { // Error
            reject(msg);
          }
        );
    });
    return promise;
  }

Here is the actual error I get from the http request that was sent to AWS S3 as a pre-signed upload url –

InvalidArgumentOnly one auth mechanism
allowed; only the X-Amz-Algorithm query parameter, Signature query
string parameter or the Authorization header should be
specifiedAuthorizationBearer
–bearer—-requestId—-hostId–

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật