Skip to content

Instantly share code, notes, and snippets.

@koo6357
Created September 9, 2019 07:44
Show Gist options
  • Save koo6357/345fb97f13a942298bf0c20ff70c4427 to your computer and use it in GitHub Desktop.
Save koo6357/345fb97f13a942298bf0c20ff70c4427 to your computer and use it in GitHub Desktop.
s3 imageUpload

aws-sdk s3 upload

  • image를 base64로 encoding된 파일을 받은경우, tag를 원할경우는 tag도 추가가능
  const s3ImageUploader = async (base64FileStr, _filename, tag) => {
    const split_str = base64FileStr.split(';base64,');
    const binaryImageData = split_str[1];
    const content_type = split_str[0].split(':')[1];
    let ext = content_type.split('/')[1];
    if(content_type === 'image/svg+xml') {
      ext = 'svg'
    }
  
    const buf = Buffer.from(binaryImageData,'base64');
    const svg = Buffer.from(binaryImageData, 'base64').toString();
  
    function isValidFile(extension) {
      return /(jpg|jpeg|png|gif|svg)$/.test(extension);
    }
  
    if(isValidFile(ext)){
      const filename = `${_filename}${moment().format('YYMMDDHHMMSS')}`;
  
      console.log(`@IMAGE UPLOAD TO S3[${filename}]`);
  
      let param = {
        Bucket: `image_upload`,
        Key: filename,
        ContentType: content_type
      };
  
      if(ext === 'svg') {
        param.Body = svg;
      } else {
        param.ContentEncoding = 'base64';
        param.Body = buf;
      }
  
      const options = {
        tags: [
          {
            Key: "name",
            Value: tag
          }
        ]
      };
  
      return await s3.upload(param, options, (s3err) => {
        if (s3err) {
          console.log("@@ s3err upload failed", s3err);
          logger.error(s3err);
        } else {
          console.log('succesfully uploaded the image!');
        }
      }).promise();
    } else {
      throw new Error('file type error')
    }
  };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment