Hey guys, anyone tried AWS S3 with Vue? I had prob...
# help
y
Hey guys, anyone tried AWS S3 with Vue? I had problems going through the documentation, don’t know which to refer to. Anyone of you have experience in uploading and getting files from AWS S3 bucket with Vue, would appreciate if you could list down some resources or sample app/code. Thanks!
r
The way I’ve typically done this is not directly from the frontend but via a request to a backend to create a signed URL that the frontend can use to up/download the file.
y
I see! Do you mind sharing some of you sample code? I saw this docs: https://docs.serverless-stack.com/storage There’s some part where it is confusing.
r
We do something like this in the lambda
Copy code
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

const config: S3ClientConfig = {
  region: process.env.REGION,
};

function getSignedUrlForFile(bucket: string, filename: string, operation: 'get' | 'put'): Promise<string> {
  const getObjectParams: GetObjectCommandInput = {
    Bucket: bucket,
    Key: filename,
  };
  const putObjectParams: PutObjectCommandInput = {
    Bucket: bucket,
    Key: filename,
  };
  const s3Client = new S3Client(config);
  const command = operation === 'get' ? new GetObjectCommand(getObjectParams) : new PutObjectCommand(putObjectParams);
  return getSignedUrl(s3Client, command, { expiresIn: 3600 });
}
The lambda that creates the signed URL needs to be given permissions to the S3 bucket in which the files will reside
y
S3 client will be coming from
@aws-sdk
as well?
r
yes
Copy code
import {
  S3Client,
  _Object,
  S3ClientConfig,
  PutObjectCommand,
  GetObjectCommand,
  GetObjectCommandInput,
  PutObjectCommandOutput,
  PutObjectCommandInput,
  DeleteObjectCommandInput,
  DeleteObjectCommand,
  GetObjectOutput,
  ListObjectsV2CommandInput,
  ListObjectsV2Command,
} from '@aws-sdk/client-s3';
y
Ohh nice. So in the frontend side, how would it look like after getting the presigned url?
r
It’s just a URL that allows for getting a file or creating a file, so you can use Axios or similar with it
y
Ohh, so its like returning a temporary URL that allows the client to fetch to that endpoint, and do the getting or create of file?
r
That’s right, you can determine how long the URL is valid for when you create it
f
Just to chime in guys, yeah on the frontend, u can just issue a normal PUT request to the presigned url:
Copy code
<input
        type="file"
        onChange={async (e) => {
          const [file] = e.target.files!;
          const url = await callApiToGetPresignedUrl(...);
          await fetch(url.data.presignedUrl, {
            method: "PUT",
            body: file,
          });
        }}
      />
y
Nice!