记录问题,方便回顾
1、使用elementUI的 el-upload插件进行上传。 2、使用input。
1、使用elementUI的 el-upload插件进行上传。
html:
<el-uploadref="avatar-uploader"class="avatar-uploader":show-file-list="false":auto-upload="false"action:on-change="handleChange"><img v-if="AddSubmenuData.imageUrl" :src="AddSubmenuData.imageUrl" class="avatar"><i v-else class="el-icon-plus avatar-uploader-icon"></i></el-upload>
js:
data() {return {AddSubmenuData:{id:"",pid:"",funType:1,name:"",sort:"",SystemCoding:"",remarks:"",imageUrl: ''},};},methods: {// 获取图片信息并转成base64handleChange(file, fileList){let reader = new FileReader();let fileResult = "";reader.readAsDataURL(file.raw);reader.onload = function() {fileResult = reader.result;};reader.onloadend = function() {this.AddSubmenuData.imageUrl = fileResult};}}
css:
/deep/ .avatar-uploader .el-upload {border: 1px dashed #d9d9d9;border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;margin-left: 80px;margin-bottom: 22px;}.avatar-uploader .el-upload:hover {border-color: #409EFF;}.avatar-uploader-icon {font-size: 28px;color: #8c939d;width: 178px;height: 178px;line-height: 178px;text-align: center;}.avatar {width: 178px;height: 178px;display: block;}
效果图:
2、使用input进行上传。
1)、html
首先input的type属性要改成file,如果需求是点击按钮在上传文件。可以给input加一个ref=“fileInput”,然后通过点击按钮调用input的事件:@click="$refs.fileInput.click()".
<div class="el-button--primary el-button" @click="$refs.fileInput.click()"><input type="file" ref="fileInput" accept="*" @change="getFile" style="display: none"><img src="../../assets/Infrastructure/xz.png" />添加</div>
2)、js
获取文件后就可以进行数据处理并调用接口。因为有些时候,上传文件有些是重复的,再次调用方法就是失效,所以,可以在每次上传完之后清除之前上传的文件,这样即使文件相同,也可以重复调用方法。this.$refs.fileInput.value=’’
// 获取文件数据getFile(event) {//这就是你上传的文件event.target.files[0]let formFile = new FormData();formFile.append("file", event.target.files[0]);formFile.append("apply_info_id", this.RndNum(12));formFile.append("file_type", '');//调用接口file_upload(formFile).then(res => {this.addInformation.addPoupTableData.data.push({name:res.data.name,id:res.data.id,size:(event.target.files[0].size/1024).toFixed(0) + "kb",path:res.data.path})//调用接口后清除文件this.$refs.fileInput.value=''})},