0
votes

I am using Angular V6 and aws-sdk package to upload files in AWS S3 bucket using Prime NG file upload library.

I am trying to upload the PDF file using below code, file is uploading in S3 bucket but, when I open the same file, it is showing error that content is corrupted

I tried multiple way, but not getting any luck.

Below is my code:

const files = event.files
    const fileReader = new FileReader();
    if (files && files.length) {
      const fileToRead = files[0];
      if (fileToRead) {
        fileReader.onload = function (fileLoadedEvent) {
          const textFromFileLoaded = fileLoadedEvent.target['result'];
          if (textFromFileLoaded) {
            var bucket = new AWS.S3({ params: { 'Bucket': 'bucket-name' } });
            let content = textFromFileLoaded
            const params = {
              Bucket: "bucket-name/path",
              Key: "filename.ext",
              Body: content,
            };
            bucket.upload(params, function (err, data) {
                // handle the rest part
            })
          }
        }
        fileReader.readAsText(fileToRead, "UTF-8");
      }
    }

I want to upload any kind of file using the same File upload Library.

1

1 Answers

0
votes

I found the solution:

The problem was - I was directly passing the content of file to the body of S3 bucket using fileReader method.

The solution is - Directly pass the files[0] to body of s3 bucket, no need to read the file and get the content.

Here is the simple code:

uploadFile(event, type) {
    const file = event.files[0]
    if (file) {
        var bucket = new AWS.S3({ params: { 'Bucket': 'bucket-name' } });
        const params = {
            Bucket: "bucket_name/path",
            Key: filename.ext,
            Body: file ,
        };
        bucket.upload(params, function (err, data) {
            handle the rest part
        })
    }
}

Reference link to understand the flow.