【问题标题】:How can I send FormData with axios patch request?如何使用 axios 补丁请求发送 FormData?
【发布时间】:2019-01-03 09:50:17
【问题描述】:

我想部分更新一组数据和一个图像文件。我的图像已更新,但其他数据未更新。 这是我的代码示例:

    updateUsersData() {
    const { gender, phone, address, cityId, image, signature } = this.state;
    const fd = new FormData();
    fd.append('image', image, image.name);
    fd.append('gender', gender);
    fd.append('phone', phone);
    fd.append('address', address);
    fd.append('cityId', cityId);
    fd.append('signature', signature);
    fd.append('_method', 'PATCH');
    API.patch(`users/${this.props.id}`, 
        fd
        )
        .then(res => {

        })
        .catch(err => console.log(err))
}

【问题讨论】:

    标签: reactjs axios multipartform-data form-data


    【解决方案1】:

    我认为,代码对你有用

    updateUsersData() {
    
      const { gender, phone, address, cityId, image, signature } = this.state;
      const fd = new FormData();
      fd.append('image', image, image.name);
      fd.append('gender', gender);
      fd.append('phone', phone);
      fd.append('address', address);
      fd.append('cityId', cityId);
      fd.append('signature', signature);
      fd.append('_method', 'PATCH');
    
      axios.post(
        `users/${this.props.id}`,
        fd,
        { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
      );
    }
    

    https://github.com/axios/axios/issues/97

    【讨论】:

    • 这里重要的是你做了axios.post() 并且你包含了一个带有_methodPATCH 的键。无论如何,对于 Laravel,这似乎是必需的方法。你不能这样做axios.patch()
    【解决方案2】:

    axios.patch() 不接受 FormData

    但是,它确实接受JSON

    然后您可以将 FormData 映射到 JSON。或者您可以从一开始就使用 JSON...

    let userData = {};
    fd.forEach(function(value, key){
        userData[key] = value;
    });
    
    axios.patch(`users/${this.props.id}`, userData);
    

    我很确定您不需要明确定义标题。 Axios 似乎在内部这样做。

    注意:

    patch 方法用于更新资源的一部分(只是电子邮件和性别等...)

    put 方法用于整体更新资源。

    编辑:更简洁的方法

    更简洁的方法是从 ref 中获取整个表单。 为此,您需要从 react 导入 useRef 并将其与您的表单挂钩(例如 ref='formRef'),然后您不需要附加任何内容,您可以像这样获取表单数据:

    let fd = new FormData(formRef.current); // grabs form data as is
    let userData = {}; // creates a user json
    fd.forEach(function(value, key){
        userData[key] = value;  // populates user json with form data
    });
    
    axios.patch(`users/${this.props.id}`, userData);  // send user json to patch this resource
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-01
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 2022-01-10
      相关资源
      最近更新 更多