analogcoding

8/7 - 4주 프로젝트 본문

Be well coding/In Immersive

8/7 - 4주 프로젝트

be well 2019. 8. 7. 23:57

Toy 47번 문제.

오늘도 ~~ to do later~~


ant design 의  upload 컴포넌트와 fetch  , 서버에서 multer 를 이용해서 이미지 file 을 url 로 db 에 저장하는 방식을 구현하는데

 

결과는 좋지 못했지만 시도했던 것을 적어본다. 현재 프론트 파트를 맡아서 서버 쪽 코드는 아직 코드리뷰를 하지 않아서 잘 알지 못하는

 

상태다.  multer 와 S3 를 이용한 방식에 대해서 다시 공부하고 포스팅 예정!

 

시도 과정

 

먼저 ant design 의 upload 태그를 import 한 후 정보가 업로드 되게 할 이벤트 태그를 감싸준다.

<Upload {...props}>
	<Button>
		<Icon type="upload" />
			upload / change
	</Button>
</Upload>

..props  로 사용된 props 에서는 여러 속성을 가지고  onChange 함수의 인자 안 file 의 상태에 따라 메세지를 띄워주고

그 후 status 가 done (업로드 완료) 일 때 업로드 된 파일을 fetch 에 바디에 fromData 로 담아서 보내줄 계획이었다.

const props = {
            name: 'file',
            action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',

            onChange(info: any) {
              if (info.file.status !== 'uploading') {
                console.log('--->', info.file, 'list-->', info.fileList);
              }
              if (info.file.status === 'done') {
                message.success(`${info.file.name} file uploaded successfully`);
                let formData = new FormData();
                formData.append('photo', info.fileList[0]);
                fetch('http://localhost:4000/', {
                  method: 'POST',
                  body: formData,
                  headers: {
                    authorization: 'authorization-text',
                    'content-type': 'multipart/form-data',
                  },
                })
                  // .then(res => res.json())
                  .then(json => console.log(json))
                  .catch(err => console.error('Caught error: ', err));
              } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
              }
            },
          };

stackoverflow , antdesign DOCS , 여러 기술 블로그 등을 참조하였지만 여전히 답을 찾지 못했다..

 

어디선 헤더를 비우고 .. 비우면 option error 가 발생하고 .. 해결하면 bundler? error 가 발생하고.. 또 다른 시도를 하면 

 

action 속성에서 걸리는 지 파일 자체 업로드가 실패하는 경우도 있었다. 400 과 500 을 내뿜으며 결국 오늘 해결 실패.

 

내일 엔지니어님께 질문 예정.. 현 프로젝트에 꽃? 이라고 할 수 있는 사진 업로드 기능이 이렇게 무너지다니.. 내일은 기필코 ㅠㅠ

 


ant Design form 태그 사용.

 

여러 태그들을  form 이라는 태그로 묶어 onSubmit 으로 모든 value 들의 값을 가져올 수 있었다. 정확히 이해하고 사용하다기보다

 

여러 글들을 참조하면서 오류를 해결하면서 사용했다.

 

컴포넌트 옆에 <{} & FormComponentProps> 를 선언하고 form.validateFields 에 인자로 values 를 넣어서 모아준다??

class Rescue extends Component<{} & FormComponentProps> {
  handleSubmit = (e: any) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log(Object.values(values).join(','));
        let result = Object.values(values).join(',');
        this.setState({
          result: result,
        });
      }
    });
  };

form 태그 안에 태그의 value 를 전달한다.

<Form.Item label="Detail">
            {getFieldDecorator('detail', {
              rules: [
                { required: true, message: 'Please input detail location!' },
              ],
            })(<Input />)}
          </Form.Item>

또 특이한 점은 하단에 Form.create 를 사용해서 class 명을 넣어준 값을 export 해줘야 error 가 사라졌다.

const WrappedNormalLoginForm = Form.create({ name: 'normal_login' })(Rescue);
export default WrappedNormalLoginForm;

 

정말 하나도 이해 못하고 기능 구현에 급급해서 진행한 것 같다.. css 고자에게 희망인 ant design 도 이렇게 어렵다..

 

이제 프로젝트 예상 마무리 날까지 일주일도 남지 않았다.. 막판 스퍼트 파이팅!

'Be well coding > In Immersive' 카테고리의 다른 글

8/9 - 4주 프로젝트  (0) 2019.08.11
8/8 - 4주 프로젝트  (0) 2019.08.08
8/6 - 4주 프로젝트  (0) 2019.08.06
8/5 - 4주 프로젝트  (0) 2019.08.06
8/3 - 4주 프로젝트  (0) 2019.08.05
Comments