Vue axios FormData对象转换附加值

问题描述 投票:1回答:2

我正在使用axios上传多个文件和其他一些东西。其中包括整数数组(来自复选框)和一些布尔值。

起初我试过这个:

axios.post(this.route, {
    name: this.name,
    ...
    photos: this.photos
})

除了后端收到照片作为空物之外,一切都很完美。所以我尝试了以下内容

let formData = new FormData()
formData.append('name', this.name)
...
for(let i = 0; i < this.photos.length; i++) {
     let photo = this.photos[i]

     formData.append('photos['+i+']', photo)
}
axios.post(this.route, formData)

照片工作得很好,但其他数据如数组和来自无线电的布尔值开始出错。 FormData将它们转换为strin,在后端直接接收数组和布尔值之前,我想要它。我使用Laravel作为后端,验证没有通过这种方式。

laravel vue.js axios form-data
2个回答
1
投票

如果要上载文件和其他结构化JSON数据,则需要手动JSON字符串化所有其他数据以及文件。

这是一个例子:

const fd = new FormData()

// Include file
fd.append('photo', file)

// Include JSON
fd.append('data', JSON.stringify({
  name: 'Bob',
  age: 20,
  registered: true,
})

axios.post('/users', fd)

在服务器上,您还需要使用data手动JSON解析json_decode字段(抱歉,我不熟悉Laravel或PHP)。


0
投票

我设法让formdata以我想要的方式发送数据。我希望有一个更简单的方法,但这就是我所做的。

        let formData = new FormData()
        formData.append('name', this.name)
        formData.append('phone', this.phone)
        formData.append('email', this.email)
        formData.append('house_state', this.house_state)

        // The boolean values were passed as "true" or "false" but now I pass them as "0" or "1" which is strill a string but Laravel recognizes it as an indicator of true or false
        formData.append('has_lived_soon', this.has_lived_soon ? 1 : 0)
        formData.append('can_rent_now', this.can_rent_now ? 1 : 0)

        formData.append('beds_count', this.beds_count)
        formData.append('seasonality', this.seasonality)

        // Here's what I do for the arrays
        for(let extra of this.extras_values) {
            formData.append('extras[]', extra)
        }

        formData.append('estate_issues', this.estate_issues ? 1 : 0)
        formData.append('road_state', this.road_state)
        formData.append('usability', this.usability ? 1 : 0)

        for(let heating_method of this.heating_values) {
            formData.append('heating_methods[]', heating_method)
        }

        formData.append('heating_other', this.heating_other)
        formData.append('address', this.address)

        for(let i = 0; i < this.photos.length; i++) {
            let photo = this.photos[i]

            formData.append('photos['+i+']', photo)
        }

        axios.post(this.route, formData)
            .then(function(response) {
                console.log(response.data)
            })
            .catch(function(error) {
                app.errors = error.response.data.errors
            })
© www.soinside.com 2019 - 2024. All rights reserved.