在vue中使用iview-ui表单中提交图片
获取图片文件使用了iviewui的upload组件来获取图片文件<Upload :action="" :before-upload="handleBeforeUpload"><Button icon="ios-cloud-upload-outline">Upload files</Button>...
·
获取图片文件
使用了iviewui的upload组件来获取图片文件
<Upload :action="" :before-upload="handleBeforeUpload">
<Button icon="ios-cloud-upload-outline">Upload files</Button>
</Upload>
同时由于不是真的需要上传到对应的地址, 所以设置before-upload对应的函数使其返回false终止上传
handleBeforeUpload(file){
this.form_submit.picture = file
return false
},
此时, 在form_submit就已经拿到文件了
上传
submit(){
// 设置请求头为 'Content-Type': 'multipart/form-data', 使请求可以上传图片
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
// 将json转换为FormData类型的数据
let formData = new FormData();
for(let key in this.form_submit){
formData.append(key, this.form_submit[key])
}
// 发送请求
postImage(formData,config).then(res => {
console.log(res.data)
})
}
源码
<template>
<div>
<div @click="addscreen">
<Card >
<p style="font-size: 22px;">新增图片</p>
</Card>
</div>
<Modal
v-model="modal"
title="添加图片"
@on-ok="submit"
>
<Form :model="form_submit" :label-width="80">
<FormItem label="标题" >
<Input v-model="form_submit.title" placeholder="请输入标题"/>
</FormItem>
<FormItem label="描述" >
<Input v-model="form_submit.description" placeholder="请输入描述"/>
</FormItem>
<FormItem label="图片" >
<Upload :action="" :before-upload="handleBeforeUpload">
<Button icon="ios-cloud-upload-outline">Upload files</Button>
</Upload>
</FormItem>
</Form>
</Modal>
</div>
</template>
<script>
import { postImage } from "./api"
export default {
name: "add-image",
components: {
},
data () {
return {
modal: false,
form_submit: {
title: '',
description: '',
picture: '',
},
}
},
methods:{
addscreen(){
this.modal = true
},
handleBeforeUpload(file){
this.form_submit.picture = file
return false
},
submit(){
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
let formData = new FormData();
for(let key in this.form_submit){
formData.append(key, this.form_submit[key])
}
postImage(formData,config).then(res => {
console.log(res.data)
})
}
},
}
</script>
<style scoped>
</style>
更多推荐
已为社区贡献1条内容
所有评论(0)