Vue.js Carrierwave:将图像从vue前端上传到rails api
我不知道如何为图像制作axios post 这就是我的json对象的外观Vue.js Carrierwave:将图像从vue前端上传到rails api,vue.js,rails-api,Vue.js,Rails Api,我不知道如何为图像制作axios post 这就是我的json对象的外观 { "id":20, "title":"pineapple", "text":"pineapple", "date":null, "created_at":"2019-03-23T01:42:48.142Z", "updated_at":"2019-03-23T01:42:48.142Z", "image":{ "url":null } } 这是我从Vue表单输入的图
{
"id":20,
"title":"pineapple",
"text":"pineapple",
"date":null,
"created_at":"2019-03-23T01:42:48.142Z",
"updated_at":"2019-03-23T01:42:48.142Z",
"image":{
"url":null
}
}
这是我从Vue表单输入的图像
<input type="file"
id="file"
ref="myFiles"
class="custom-file-input"
@change="takeFile"
multiple>
这里是指向my中文件的链接。首先此。$refs.myFiles.files返回一个文件数组。更改如下方法以将文件设置为blog.link:
takeFileevent{
this.blog.link=this.$refs.myFiles.files[0]
}
现在,要在post请求中发送文件,您应该使用:
亚博客{
设formData=newformdata
formData.appendarticle[title],blog.title
formData.appendarticle[text],blog.content
formData.appendarticle[image],blog.link
axios.post'http://localhost:3000/articles,formData{
标题:{
“内容类型”:“应用程序/json”
}
}.功能反应{
console.logresponse
}.catchfunction错误{
控制台日志错误
}
},
尝试此takeFileevent{let image=event.target.files[0]let reader=new FileReader.readAsDataURLimage reader.onload=e=>{this.blog.link=e.target.result}},然后在axios post请求中添加标题:{'Content Type':'multipart/form data'},谢谢您的帮助。我试过了,但由于某种原因,它不起作用。这真的很有帮助。非常感谢你。
export default {
data() {
return {
blog: {
title: '',
content: '',
link: ''
}
}
},
methods: {
submitArticle(blog) {
console.log('blog.link', blog.link)
axios.post('http://localhost:3000/articles', {
title: blog.title,
text: blog.content,
image: {
url: blog.link
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
},
takeFile(event) {
console.log(this.$refs.myFiles.files);
this.blog.link = this.$refs.myFiles.files
}
}
}