代码
<el-button type="primary" @click="dialogFormVisible = true,form = {}">新增</el-button>
<el-dialog title="新增" :visible.sync="dialogFormVisible">
<el-form ref="form" :model="form" label-width="80px">
<el-form-item label="照片名称">
<el-input v-model="form.picture_name"></el-input>
</el-form-item>
<el-upload
ref="upload"
name="multipartFile"
list-type="picture-card"
accept="image/jpeg,image/gif,image/png"
:limit="1"
:auto-upload="false"
:on-preview="handlePictureCardPreview"
:action="doUpload"
:on-success="handleSucceed">
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl">
</el-dialog>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogFormVisible = false,submitUpload()">确 定</el-button>
</div>
</el-dialog>
<script type="text/javascript">
new Vue({
el:"#app",
data(){
return {
//文件上传
doUpload:'http://localhost:8087/AjaxServer/TPicture/uploadFile.do',
dialogImageUrl: '',
dialogVisible: false,
//表单
dialogFormVisible: false,
form:{noid:'',picture_name:'',relative_path:''},
}
},
methods: {
submitUpload() {
let picture_name = this.form.picture_name;
let flag = this.$refs.upload.uploadFiles;
if(picture_name==""||picture_name==undefined||flag==0){
this.$message({
showClose: true,
message: '警告:信息不能为空!',
type: 'warning'
});
}else{
this.$refs.upload.submit();
}
},
//如果图片上传成功就触发
handleSucceed(response, file, fileList){
if(response.code==0){
this.form.relative_path = response.data;
let url = "http://localhost:8087/AjaxServer/TPicture/insert.do";
let d1 = {
'picture_name':this.form.picture_name,
'relative_path':this.form.relative_path
};
axios.post(url,d1).then((resp)=>{
if(resp.data.code==0){
this.$message({
showClose: true,
message: '添加成功',
type: 'success'
});
this.init();
}
})
}else{
this.$message.error(response.msg);
}
//清空图片列表
this.$refs.upload.clearFiles();
},
//点击产看图片触发
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
}
})
</script>
解释:ref="upload"
这个是:上文件控件的名字 就好比是对象,可利用这个名字upload 来调用控件里的的方法
解释:action="http://localhost:8087/AjaxServer/TPicture/uploadFile.do"
这个是:必选参数,上传的地址
解释::auto-upload="false"
是否在选取文件后立即进行上传 true:是开启自动提交
解释:name="multipartFile"
这个是:上传的文件字段名 要和Controller 的参数名对应上 "MultipartFile multipartFile"
@RequestMapping("/uploadFile.do")
public ResultBean uploadFile(MultipartFile multipartFile) throws IOException {
return tPictureService.uploadFile(multipartFile);
}
解释:accept="image/jpeg,image/gif,image/png"
这个是:控制用户 上传文件的类型
解释::limit="1"
这个是:限制文件列表显示的个数
解释:list-type="picture-card"
这个是:文件列表的类型 可选值: text/picture/picture-card