티스토리 뷰

React:

리액트 컴포넌트와 AWS S3연동해 사진 올리고 그 정보 받아오기


https://www.beforecoding.net/nodejs/fileupload 참고


[Back end]


| API 서버 초기 설정 쪽


const fileUpload = require('express-fileupload');
app.use(fileUpload());

//추가


| 라우터 쪽


# router.js


router.post('/v3/menus/uploadImage', menus.uploadImage);


# menus.js


var AWS = require('aws-sdk');

async function uploadImage(req, res) {
 const file = req.files.file;
 //아마존 S3에 저장하려면 먼저 설정을 업데이트합니다.
 AWS.config.region = 'ap-northeast-2'; //Seoul
 AWS.config.update({
   accessKeyId: process.env.ACCESS_KEY_ID,
   secretAccessKey: process.env.SECRET_ACCESS_KEY,
});

 var s3_params = {
   Bucket: 버킷이름,
   Key: `저장할 경로/${file.name}`,
   ACL: 'public-read',
   ContentType: file.mimetype,
   Body: file.data,
};
 var s3obj = new AWS.S3({ params: s3_params });
 s3obj
  .upload()
  .on('httpUploadProgress', function(evt) {})
  .send(function(err, data) {
     //S3 File URL
     res.status(200).send(data.key);
     //어디에서나 브라우저를 통해 접근할 수 있는 파일 URL을 얻었습니다.
  });
}

[Front end]


| 리액트 컴포넌트 쪽


import React, { Component } from "react";
import axios from "axios";
import classnames from "classnames/bind";

import css from "./FileUploader.scss";

const cx = classnames.bind(css);
const moduleName = "FileUploader";

class FileUploader extends Component {
 constructor(props) {
   super(props);
   this.state = {
     uploadStatus: false
  };
   this.handleUpload = this.handleUpload.bind(this);
}

 handleUpload(ev) {
   const updateValue = this.props.handleChange;
   ev.preventDefault();

   const data = new FormData();
   data.append("file", this.uploadInput.files[0]);
   data.append("filename", this.uploadInput.files[0].name);
   axios
    .post(
       `이미지 업로드할 api route`,
       data
    )
    .then(function(response) {
console.log(response)// 옆과 같이 response를 로그를 찍어볼수 있습니다. 여기서 setState등의 작업 을 통해 aws s3 에 올라간 이미지 정보를 저장할 수 있다.
    })
    .catch(function(error) {
       console.log(error);
    });
}
 render() {
   return (
     <div className={cx(`${moduleName}`)}>
       <form enctype="multipart/form-data" onSubmit={this.handleUpload}>
         <div className="form-group">
           <input
             className="form-control"
             ref={ref => {
               this.uploadInput = ref;
            }}
             type="file"
           />
         </div>

         <button className="btn btn-success" type="submit">
          Upload
         </button>
       </form>
     </div>
  );
}
}

export default FileUploader;

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함