본문 바로가기
Web/Frontend

[리액트] 이미지 업로더 - 서버에 이미지 Post로 보내기

by r4bb1t 2020. 7. 20.
반응형

https://r4bb1t.tistory.com/29를 이용해 클라이언트에서 서버에 이미지를 업로드하면 그 이미지를 표시해주는 업로더를 만들어보자.

클라이언트 |

import React, { useState} from "react";
import * as S from "./styles";
import axios from "axios";
import AddAPhotoIcon from "@material-ui/icons/AddPhotoAlternate";

function ImageUploader() {
  const [imageUrl, setImageUrl] = useState("디폴트 이미지 주소");
  const setFile = (e) => {};
  return (
    <>
      <S.ProfileImage src={imageUrl} />
      <S.Overlay>
        <AddAPhotoIcon style={{ color: "lightgray", fontSize: 60 }} />
        <S.Input type="file" accept="image/*" onChange={(e) => setFile(e)} />
      </S.Overlay>
    </>
  );
}

export default ImageUploader;

 

우선 기본 틀을 짜준다.

이미지를 표시하는 ProfileImage 컴포넌트에는 src를 imageUrl이라는 state로 주었다.

Input 컴포넌트에서 이미지 파일이 입력되었을 때 imageUrl을 바꿔주면 알아서 바뀐 이미지로 표시할 것이다.

Overlay 컴포넌트는 hover 시에 검은 색으로 오버레이되고 커서가 포인터로 바뀌는 것 외의 기능은 없다.

 

그리고 setFile 함수가 중요한데, 일단 http통신 라이브러리인 axios를 설치해주자.

$ npm install --save axios

슥삭

 

const setFile = (e) => {
  if (e.target.files[0]) {
    const img = new FormData();
    img.append("file", e.target.files[0]);
    axios
      .post("http://localhost:8080/upload", img)
      .then((res) => {
        setImageUrl(res.data);
      })
      .catch((err) => {
        console.error(err);
      });
  }
};

해당 링크로 post에 업로드된 파일을 보내고, 응답으로 받아온 url을 imageUrl에 넣어주면 끝!

 

서버 |

이 글에서 많이 수정은 하지 않았다.

다만 이번에는 클라이언트에서 서버에 요청을 보내기 때문에 CORS 설정을 해 주었다.

$ npm install --save cors
$ npm install --save-dev @types/cors

cors 모듈을 설치해준다.

 

import cors from "cors";

const corsOptions = {
  origin: "http://localhost:3000",
  credentials: true,
};

app.use(cors(corsOptions));

 

코드를 추가해준다. 간단하다.

 

이렇게 간단한데 처음에는 안 됐는데, 클라이언트에서 "http://localhost:8080/upload"라고 쓰지 않고 "localhost:8080/upload"라고 썼기 때문인 듯 하다.

일단 로컬에서는 잘 작동되는데, 실제 서버에 적용하려면 조금 더 고민을 해봐야 할 것 같다.

 

 

반응형

댓글