이번 프로젝트에서 이미지 관리를 프론트엔드쪽에서 관리하기로 했다!
회사별로 이미지 DB 관리 하는 방식이 다 다른데 이번에는 프론트에서 관리를 하고
data.location (url 형식)만 백으로 전달해주기로 했다.
AWS에서 S3 Bucket에 사진을 넣으려면 react-aws-s3를 먼저 설치해줘야 한다.
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>
혹시 이미지를 불러오는 기능은 없는건가용..?