[React/Basic] Axios Image Upload, Form Data Handling

column clash·2022년 6월 19일
0
// Image Upload Basic

import React from 'react';
import axios from 'axios';

const Form = () => {
  // a local state to store the currently selected file.
  const [selectedFile, setSelectedFile] = React.useState(null);

  const handleSubmit = (event) => {
    event.preventDefault()
    const formData = new FormData();
    formData.append("selectedFile", selectedFile);
    try {
      const response = await axios({
        method: "post",
        url: "/api/upload/file",
        data: formData,
        headers: { "Content-Type": "multipart/form-data" },
      });
    } catch(error) {
      console.log(error)
    }
  }

  const handleFileSelect = (event) => {
    setSelectedFile(event.target.files[0])
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" onChange={handleFileSelect}/>
      <input type="submit" value="Upload File" />
    </form>
  )
};

export default Form;

axios의 content-type은 자동으로 multipart/form-data가 되기 때문에 굳이 지정할 필요가 없지만, 확실하게 하기 위하여 지정하였다.

// Form Data

import React from 'react';
import axios from 'axios';

const LoginForm = () => {
  
  const [formValue, setformValue] = React.useState({
    email: '',
    password: ''
  });

  const handleSubmit = (event) => {
    // we will fill this in the coming paragraph
  }

  const handleChange = (event) => {
    setformValue({
      ...formValue,
      [event.target.name]: event.target.value
    });
  }

  return (
    <form onSubmit={handleSubmit}>
      <p>Login Form</p>
      <input
        type="email"
        name="email"
        placeholder="enter an email"
        value={formValue.email}
        onChange={handleChange}
      />
      <input
        type="password"
        name="password"
        placeholder="enter a password"
        value={formValue.password}
        onChange={handleChange}
      />
      <button
        type="submit"
      >
        Login
      </button>
    </form>
  )
};

export default LoginForm;


const handleSubmit = async() => {
  // store the states in the form data
  const loginFormData = new FormData();
  loginFormData.append("username", formValue.email)
  loginFormData.append("password", formValue.password)

  try {
    // make axios post request
    const response = await axios({
      method: "post",
      url: "/api/login",
      data: loginFormData,
      headers: { "Content-Type": "multipart/form-data" },
    });
  } catch(error) {
    console.log(error)
  }
}

---


Drop 핸들러

profile
풀스택 개발 중...

0개의 댓글