【问题标题】:Sending photo with vuejs使用 vuejs 发送照片
【发布时间】:2020-05-06 01:47:50
【问题描述】:

我正在使用ElementUi uploader,我需要将我的文件与我的其余表单数据一起发送,但它似乎没有将照片的正确详细信息发送到后端:

截图

Console log when i select an image

Data that sent to back-end

代码

photo input

<el-upload
    action="#"
    :limit="1"
    :multiple="false"
    :on-change="photoChanged"
    :on-exceed="handleExceed"
    list-type="picture-card"
    :on-remove="handleRemove"
    :on-preview="handlePictureCardPreview"
    :before-remove="beforeRemove"
    :auto-upload="false">
    <i slot="default" class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
    <img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>

Script

export default {
    data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false,
            form: {
                name: '',
                slug: '',
                price: '',
                new_price: '',
                sku: '',
                qty: 1,
                active: '',
                photo: '',
                shortDesc: '',
                longDesc: '',
                region: '',
                date1: '',
                date2: '',
                type: [],
                tags: [],
                brand_id: '',
                categories: [],
                resource: '',
                user_id: ''
            }
        }
    },
    methods: {
        onSubmit(e) { //send data to back-end
            e.preventDefault();
            axios.post('/api/admin/products/store', this.form)
            .then(res => {
                console.log(res);
            })
            .catch(error => {
                console.log(error);
            })
        },
        handleRemove(file) {
            this.form.photo = ''; // remove photo from from when it's removed
        },
        photoChanged(file, fileList){
            this.form.photo = file.raw;  // add photo to form when it's selected
            console.log('file', file) // screenshot 1
            console.log('raw', file.raw) //screenshot 2
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleExceed(files, fileList) {
            this.$message.warning(`The limit is 1, you selected ${files.length} files this time, add up to ${files.length + fileList.length} totally, remove old image and try again.`);
        },
        beforeRemove(file) {
            return this.$confirm(`Cancel the transfert of ${ file.name } ?`);
        }
    },
  }
</script>

有什么想法吗?

【问题讨论】:

  • 把你的文件转换成base64然后就可以了。
  • @Qonvex620 怎么办?

标签: javascript laravel vue.js element-ui


【解决方案1】:

我使用 FormData 将照片或文档发送到服务器。 JavaScript FormData

  <form id="myForm" name="myForm">
    <div>
        <label for="username">Enter name:</label>
        <input type="text" id="username" name="username" v-model="imageData.name">
      </div>
     <div>
        <label for="useracc">Enter account number:</label>
        <input type="text" id="useracc" name="useracc" v-model="imageData.account">
      </div>
    <label for="userfile">Upload file:</label>
    <input type="file" id="userfile" name="userfile">
  </div>
  <input type="submit" value="Submit!">
</form>

export default {
    data() {
        return { 
            imageData: {}
        }
    },
    methods: {
        uploadImageToServer() {
            // 1.Save the form Data and return the new id to save the image 
            axios.post('/api/admin/products/store', this.imageData)
            .then(res => {
                if(res.id) {
                //2. Save the image to id
                let formData = new FormData();
                let file = document.getElementById('userfile');
                formData.append('file', file)
                axios.post('/api/admin/products/image/{id}', formData)
                    .then(res => {
                        console.log(res)
                    })
                }
            })
            .catch(err => {
                console.log(err)
            }) 

        }
    }
}

在这里, 表单数据和文件数据都不能在单个请求中发送。 1. 保存表单数据并返回id。 2. 保存图片数据到id。 用 'element-ui' 语法替换 html。确保您的 rest api 接收表单数据作为输入。

【讨论】:

  • 是的,但问题在于 el-upload&gt; 标签处理图像数据的方式,否则它不会成为问题,formData 可以正常工作。
【解决方案2】:

已解决

好吧,我决定放弃将带有其余数据的图像发送到后端,并首先在我的输入中使用action="#" 上传图像,作为回报,我在表单中获取文件名,然后将文件名与表单的其余部分一起发送而不是发送图像文件。

<el-upload
  action="/api/upload"
  :on-success="handleAvatarSuccess"
.....>


methods: {
  handleAvatarSuccess(res, file) {
    this.form.photo = res.data;
  },
}

因此,它会在选择我的文件后立即将其发送到后端,并在我的 form.photo 中设置存储文件的名称,该名称将与我的其他表单输入一起发送。

希望它对其他人也有用。

【讨论】:

    【解决方案3】:

    将您的文件转换为 base64

    当你选择一张图片时,使用下面的代码

           onImageChange() {
              let file = this.form.photo
    
              if (file == '')
                    return;
    
               this.createImage(file);
           }
    
           createImage(file) {
               let reader = new FileReader();
               let el = this
               reader.onload = (e) => {
                    el.form.photo = e.target.files[0];      
               };
               reader.readAsDataURL(file);
           },
    

    在您的输入文件中附加 onImageChange 函数

    【讨论】:

    • 当我选择文件时它返回Error in v-on handler: "TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'."
    • 还是Error in v-on handler: "TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'."
    • 如何在 onImageChange 函数中传递文件?,也许你没有传递文件
    • 基本上我只使用您的createImage 函数并将名称更改为photoChanged,因为我的photoChanged 正在更改方法:on-change="photoChanged" 所以该文件肯定存在,但有些我们无法用fileReader()阅读它
    • photoChanged(file) { let reader = new FileReader(); reader.onload = (e) =&gt; { this.form.photo = e.target.files[0]; }; reader.readAsDataURL(file); },
    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2021-12-12
    • 1970-01-01
    • 2015-11-24
    相关资源
    最近更新 更多