如何通过Axios将文件和数据发布在一起



我正在尝试发布数据(在Vue应用程序中(。表单中还有一个图像文件输入。所有教程和答案都只是告诉你单独发送文件或与其他文件一起发送。[1] [2]

我想做的是将文件附加到我使用v-model绑定创建的现有对象中。

// Vue
<template>
<input name="title" type="text" v-model="newPost.title" />
<textarea name="content" v-model="newPost.content"></textarea>
<input name="image" type="file" />
</template>
<script>
...
newPost: {
title: null,
image: null,
content: null
}
...
addNewPost() {
axios.post('/api/posts', this.newPost)
}
</script>

我该怎么做?

您可以在客户端使用Base64编码,并将编码后的字符串添加到您的post请求中,然后从服务器端解码:这里的图片将是一个编码字符串,你可以发送axios请求,正如你写的。

您无法使用v-model装载所选文件。由于文件是一个不断变化的元素,因此应该使用@changeref属性。

<input name="image" type="file" @change="selectedPostImage" ref="postImage"/>

在捕获所选文件的函数中执行以下操作。

selectedPostImage(){
this.newPost.image= this.$refs.postImage.files[0]
}

完成这些步骤后,您可以使用axios发送数据。好的编码。。

最新更新