之前做的都是自动上传,通过上传成功的回调来判断,这次需求要手动上传,所以记录一下。
<template>
<div>
<el-upload class="upload-demo" ref="upload" :action="upload_url" :auto-upload="false"
:before-upload="beforeAvatarUpload" :on-change="handleChange" :on-remove="handleRemove"
:on-preview="handlePreview" multiple :limit="1" :file-list="fileList" accept=".jpg,.png">
<el-button size="small" type="primary">点击选择</el-button>
<div slot="tip" class="el-upload__tip">选择.jpg或.png格式文件</div>
</el-upload>
<el-button style="margin: 30px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
</div>
</template>
<script>
export default {
data() {
return {
upload_url: 'xxx',
fileList: [],
isClientCertFile: true,
uploadForm: new FormData(),
imgFile: [],
}
},
methods: {
// 点击上传
submitUpload() {
if (this.isClientCertFile) {
this.$message.error("请上传证书文件")
return
}
this.$refs.upload.submit();
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/demo", true);
xhr.send(this.uploadForm);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {}
}
}
},
//值改变 判读是否有值
handleChange(file, fileList, name) {
this.imgFile["file"] = fileList;
if (typeof this.imgFile.file != "undefined" && this.imgFile.file.length > 0) {
this.isClientCertFile = false;
} else {
this.isClientCertFile = true;
}
},
//值被清空
handleRemove(file, fileList, name) {
this.isClientCertFile = true;
},
// 上传前调用,假如上传的文件需要和其他输入框的信息一并提交的话,
// 那么需要把上传的文件append到this.uploadForm中 并且返回false取消上传动作,在提交的时候一并把数据传送过去。
beforeAvatarUpload(file) {
this.uploadForm.append('clientcert', file)
return false
},
//
handlePreview(file) {
console.log(file);
}
},
}
</script>