在 React 中将用户给定的图像发送到 Api

Send user given Image to Api in React

我正在尝试将图像作为输入,它将作为 formData 发送到 api。

我的代码 ->

供用户输入 ->

            <input
              type="file"
              accept="image/*"
              name="image-upload"
              id="SelectFile"
              onChange={this.imageHandler}
              style={{ display: 'none' }}
            />

imageHandler 函数 ->

  imageHandler = (e) => {
    console.log(e.target.files[0])
    const reader = new FileReader();
    reader.onloadend = function(){
      const dataURL = reader.result;
      let output = document.getElementById('input');
      output.src = dataURL;
    };
    reader.readAsDataURL(e.target.files[0]);

    let form_data = new FormData();
    form_data.append('image', e.target.files[0]);
    saveImage(form_data,this.state.userDetail.email).then(res=>{
      if(res.success){
        this.setState({
          showAlert: true,
          alertMessage: 'Image Saved',
          alertType: 'success',
        });
      }
    })
  }; 

saveImage 函数调用 api ->

export const saveImage = async (data,email) => {
  try {
    const response = await axios.post(`${commonApi.api}/user-image`, data, {
      headers: {
        'content-type': 'multipart/form-data',
        'Authorization': localStorage.getItem('token')
      },
      params:{
        userEmail: email
      }
    });
    if (response.data.success) {
      return { success: true, message: '', data: response.data.payload };
    } else {
      return { success: false, message: response.data.message };
    }
  } catch (error) {
    console.log('response',error.response.data)
    return { success: false, message: 'Failed' };
  }
};

因此,这向我抛出 403 错误。 但是当我用邮递员检查时,它工作正常。

邮递员请求图片-> https://ibb.co/HBxLWhn 所以我想我处理图像错误。 我在这里犯了什么错误?

在浪费了 2 个多小时后发现了我的问题。 header 中的 authorization 似乎区分大小写。 我写了 ->

  headers: {
    'content-type': 'multipart/form-data',
    'Authorization': localStorage.getItem('token')
  },

应该是 ->

  headers: {
    'content-type': 'multipart/form-data',
    'authorization': localStorage.getItem('token')
  },

2 小时 A xD