如何发送 v-file-input 的内容?
How to send the content of v-file-input?
我的组件是这样的:
<template>
<div>
<v-file-input accept="image/*" v-model="image"></v-file-input>
<button @click="uploadImage">Upload</button>
</div>
</template>
<script>
export default {
data(){
return {
image: null
}
},
methods: {
async uploadImage(){
await this.$axios.put('url', {image: this.image})
}
}
}
</script>
如果我单击按钮并发送请求,则请求负载为 {image: {}}
。为什么?如何发送this.image
的内容?
您可能应该使用 POST
而不是 PUT
。但是您的代码正在运行:如果您 console.log(this.image)
,您将看到该文件,浏览器中的 Vue devtools 也是如此。
我不确定如何在网络选项卡中看到它,但它已正确发送到给定的后端。我猜你只需要一个合适的后端。
这个问题在这里可能会有用:How to see form data with enctype = "multipart/form-data" in Chrome debugger
这是一个讨论 multipart/form-data
对象的 MDN 页面,即使没有关于如何查看实际负载的解决方案:https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
只需发送带有 FormData 的文件。您可以将此代码放入 uploadImage():
let form = new FormData();
form.append(file, this.file);
this.$axios.post('url', form)
然后你就可以在服务器上访问了。
来试试我做的这支代码笔
codepen v-file-input
addImage (file) {
if (file) {
const reader = new FileReader()
reader.onload = (e) => {
const imgObj = new Image()
// console.log(e.target.result)
imgObj.src = e.target.result
// console.log(imgObj)
this.imageHandler = imgObj
}
if (file) {
reader.readAsDataURL(file)
}
} else {
console.log('error')
}
}
要点:
const reader = new FileReader()
const imgObj = new Image()
imgObj.src = e.target.result
然后赋值this.imageHandler = imgObj
我的组件是这样的:
<template>
<div>
<v-file-input accept="image/*" v-model="image"></v-file-input>
<button @click="uploadImage">Upload</button>
</div>
</template>
<script>
export default {
data(){
return {
image: null
}
},
methods: {
async uploadImage(){
await this.$axios.put('url', {image: this.image})
}
}
}
</script>
如果我单击按钮并发送请求,则请求负载为 {image: {}}
。为什么?如何发送this.image
的内容?
您可能应该使用 POST
而不是 PUT
。但是您的代码正在运行:如果您 console.log(this.image)
,您将看到该文件,浏览器中的 Vue devtools 也是如此。
我不确定如何在网络选项卡中看到它,但它已正确发送到给定的后端。我猜你只需要一个合适的后端。
这个问题在这里可能会有用:How to see form data with enctype = "multipart/form-data" in Chrome debugger
这是一个讨论 multipart/form-data
对象的 MDN 页面,即使没有关于如何查看实际负载的解决方案:https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
只需发送带有 FormData 的文件。您可以将此代码放入 uploadImage():
let form = new FormData();
form.append(file, this.file);
this.$axios.post('url', form)
然后你就可以在服务器上访问了。
来试试我做的这支代码笔 codepen v-file-input
addImage (file) {
if (file) {
const reader = new FileReader()
reader.onload = (e) => {
const imgObj = new Image()
// console.log(e.target.result)
imgObj.src = e.target.result
// console.log(imgObj)
this.imageHandler = imgObj
}
if (file) {
reader.readAsDataURL(file)
}
} else {
console.log('error')
}
}
要点:
const reader = new FileReader()
const imgObj = new Image()
imgObj.src = e.target.result
然后赋值this.imageHandler = imgObj