如何使用令牌Vue JS上传图像文件

时间:2019-02-13 16:14:43

标签: image vue.js upload axios vuex

我正在尝试上传图片,以便将其发送到我的API,问题是验证需要在他们登录后保留在页面上。当我尝试通过邮递员上传图片时,它可以工作不在我的Vue代码的前端执行此操作。

如果有人知道如何更改此代码以使其正常工作,请告诉我。

<template>
  <v-app id="inspire">
    <v-content>
        <v-layout align-center justify-center>
          <v-flex xs12 sm8 md4>
            <v-card class="elevation-12">
              <v-toolbar dark color="green">
                <v-toolbar-title>Upload Images</v-toolbar-title>
                <v-spacer></v-spacer>
                  <v-btn slot="activator" icon large href="https://codepen.io/johnjleider/pen/wyYVVj" target="_blank">
                    <v-icon large>mdi-codepen</v-icon>
                  </v-btn>
              </v-toolbar>
              <v-card-text>
                <v-form class="upload" @keydown.enter="addImage" method="post">
                  <v-text-field v-model="uploadImage.title" prepend-icon="title" id="title" name="title" label="Image Title" type="text"></v-text-field>
                  <v-text-field v-model="uploadImage.description" id="description" prepend-icon="description" name="description" label="Description" type="text"></v-text-field>
                  <v-text-field v-model="uploadImage.album_path" id="ablum_path" prepend-icon="photo_album" name="album_path" label="Choose an album" type="search"></v-text-field>
                  <input @change="onFileSelected" type="file" name="image" id="image">
                </v-form>
              </v-card-text>
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn v-on:click="addImage" type="submit" color="green white--text">Upload</v-btn>
              </v-card-actions>
            </v-card>
          </v-flex>
        </v-layout>
    </v-content>
  </v-app>
</template>

<script>
    import axios from 'axios'

export default {
    data() {
        return {
          feedback: null,
          selectedFile: null,
        uploadImage: [
              { title: '' },
              { description: '' },
              { album_path: '' },
              {image: null}
            ]
        }
    }, 
    methods:{
      addImage() {
        axios.post('/api/image/upload',
          { 
            'title': this.uploadImage.title,
            'description': this.uploadImage.description,
            'album_path': this.uploadImage.album_path,
            'image': this.selectedFile,



          },


          { headers: { 'Authorization': 'Bearer ' + this.$store.state.token }
        })
        .then(response => {
          console.log("headers: {'Authorization': 'Bearer '" + this.$store.state.token);
          console.log(response);
        })

        }
    }
}
</script>

<style>
.red-text {
  color: red;
  font-size: 20px;
  text-align: center;
}
</style>

1 个答案:

答案 0 :(得分:1)

您可以在发送发布请求之前尝试将content-type添加到axios的标头中。

      "Content-Type": "multipart/form-data; boundary=----",
    },