React에서 S3 Bucket에 이미지 올리고 불러오기 (ft. AWS)

너겟·2022년 6월 16일
3
post-thumbnail

S3 Bucket에 이미지 올리고 불러오기 (ft. AWS)

이번 프로젝트에서 이미지 관리를 프론트엔드쪽에서 관리하기로 했다!

회사별로 이미지 DB 관리 하는 방식이 다 다른데 이번에는 프론트에서 관리를 하고
data.location (url 형식)만 백으로 전달해주기로 했다.

AWS에서 S3 Bucket에 사진을 넣으려면 react-aws-s3를 먼저 설치해줘야 한다.

  1. S3 설치
  2. config 정보를 .env파일에 넣어서 저장하고 불러오기
  3. 사진 한장 넣기
  4. 사진 여러장 넣기 : 사진을 한꺼번에 여러장 넣는 방법이 없는 것 같아서 한 장 넣는 방식을 반복하는 식으로 구현했다. 혹시 여러장 한꺼번에 올리는 기능이 있다면 알려주세요!!
import React, {useRef, useState} from 'react';
import S3 from 'react-aws-s3';

사진 한장 넣기

window.Buffer = window.Buffer || require("buffer").Buffer;
//file upload to storage & show preview
    const [selectedFile, setSelectedFile] = useState(item.img_url);

    const config = {
        bucketName:process.env.REACT_APP_BUCKET_NAME,
        region:process.env.REACT_APP_REGION,
        accessKeyId:process.env.REACT_APP_ACCESS,
        secretAccessKey:process.env.REACT_APP_SECRET,
    }

    const handleFileInput = (e) => {
        setSelectedFile(e.target.files[0]);
        if (e.target.files[0].name.length > 0) {
            uploadFile(e.target.files[0]);
        };
    }

    const uploadFile = async (file) => {
        const ReactS3Client = new S3(config);
        // the name of the file uploaded is used to upload it to S3
        ReactS3Client
        .uploadFile(file, file.name)
        .then((data) => {
            console.log(data.location);
            setFile(data.location);
            setSelectedFile(data.location);
            setDisplay(false);
        })
        .catch(err => console.error(err))
    }

사진 여러장 넣기

window.Buffer = window.Buffer || require("buffer").Buffer;
const [array, setArray] = useState([]);

 //file upload to storage & show preview
    const [selectedFile, setSelectedFile] = useState(item.img_url[0]);

    const config = {
        bucketName:process.env.REACT_APP_BUCKET_NAME,
        region:process.env.REACT_APP_REGION,
        accessKeyId:process.env.REACT_APP_ACCESS,
        secretAccessKey:process.env.REACT_APP_SECRET,
    }

    const arr = [];
    const handleFileInput = (e) => {
        if (e.target.files.length > 0) {
            setSelectedFile(e.target.files);
            
            const length = e.target.files.length;
            console.log(length)

            for(let i=0; i<length; i++) {
                const ReactS3Client = new S3(config);
                // the name of the file uploaded is used to upload it to S3
                ReactS3Client
                .uploadFile(e.target.files[i], e.target.files[i].name)
                .then((data) => {
                    console.log(data.location);
                    
                    arr.push(data.location);
                    console.log(arr);
                    setFile(arr[0]);
                    setArray([...arr]);
                    
                    setDisplay(false);
                })
                .catch(err => console.error(err))
            }
        }
        
    }

input file에서 여러장의 사진을 선택하고 싶다면 multiple을 추가해주면 된다!

<input className='file' type="file" multiple ref={inputFile} 
                onChange={(e)=>{
                  handleFileInput(e)
                  }}
                  
<div className='btn lg-btn' onClick={() => newpost()}>Post!</div>  
profile
꾸준하게 하는 법을 배우는 중입니다!

1개의 댓글

comment-user-thumbnail
2022년 8월 24일

혹시 이미지를 불러오는 기능은 없는건가용..?

답글 달기