Vue.js图片上传表单数据

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

我正在尝试上传Vue.js中的图像并将其发送到带有axios的服务器但是我得到了一些错误。

首先:

我试图像formData一样发送它。不是base64格式。

这是我的意见:

<label>File
   <input type="file" id="file" ref="file" v-on:change="onChangeFileUpload()"/>
</label>
<button v-on:click="submitForm()">Upload</button>

这是我的数据层和方法:

export default {
  data() {
    return {
      file: ''
           }
       },
        methods: {
           submitForm(){
            let formData = new FormData();
            formData.append('file', this.file);

            this.axios.post('apiURL',
                formData,
                {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'token': '030303039jddjdj'
                }
              }
            ).then(function(data){
              console.log(data.data);
            })
            .catch(function(){
              console.log('FAILURE!!');
            });
      },

      onChangeFileUpload(){
        this.file = this.$refs.file.files[0];
      }
    }
    }

我正在尝试在发送到服务器之前显示图像。

<img :src="file" /> 

但我无法显示图像

我收到错误:

[object%20File]:1 GET http://localhost:3000/[object%20File] 404 (Not Found)

哪里弄错了?

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

为了显示图像,您可以在图像完全上传到服务器后将URL提供给src,或者如果要在发送到服务器之前显示图像,则必须使用base64格式对文件进行编码,如此定义数据中的base64变量

    onChangeFileUpload ($event) {
      this.file = $event.files[0]
      this.encodeImage(this.file)
    },
    encodeImage (input) {
      if (input) {
        const reader = new FileReader()
        reader.onload = (e) => {
          this.base64Img = e.target.result
        }
        reader.readAsDataURL(input)
      }
    }

然后你可以检查文件是否上传你应该直接从url查看图像,否则在base64中

<img :src="base64Img" /> 

0
投票

这是生成图像的代码。

https://codepen.io/Atinux/pen/qOvawK

试试这个文件上传。

uploadFile(){
        let fd = new FormData();
        fd.append("file", this.file);

        this.axios.post('/uploadFile',fd,{
         headers: { 'Content-Type': undefined,
         'Authorization': `Bearer ${this.token}` },
        }).then(function (response) {
          if (response.data.ok) {
          }
        }.bind(this));

      }
© www.soinside.com 2019 - 2024. All rights reserved.