hi,欢迎访问本站!
当前位置: 首页学习笔记正文

vue项目 使用原生 input file 处理单个文件上传

用户投稿 学习笔记 19阅读
<el-form-item label="上传附件" prop=""> <el-button size="small" type="primary" icon="el-icon-upload" @click="selectFile">选取文件</el-button> <div v-if="fileName"> <span>{{fileName}}</span> <span class="delete" @click="deleteFile">×</span> </div> <input v-show=false type="file" id="file" ref="fileInput" @change="handleFileChange($event)" accept="fileType"></el-form-item> /*** 原生 input file 处理单个文件上传**/deleteFile() { this.fileName = ''; // this.editForm.filePath = undefined; this.editForm.imgFile = undefined; this.$refs.fileInput.value = '';},selectFile() { this.$refs.fileInput.click();},handleFileChange(event) { let fileName = event.target.files[0].name; let fileSize = event.target.files[0].size; if(fileName !== undefined) { let nowType = fileName.substring(fileName.lastIndexOf(".")); if(fileType.indexOf(nowType) === -1) { this.$message({ title: '提示', message: '不支持的文件类型', type: 'warning', duration: 2000 }) return } } if (fileSize > maxFileSize) { this.$message({ title: '提示', message: `附件大小不能大于${maxFileSize / (1024 * 1024)}M!`, type: 'warning', duration: 2000 }) return } this.editForm.imgFile = event.target.files[0]; this.fileName = this.editForm.imgFile.name let reader = new FileReader(); reader.readAsDataURL(event.target.files[0]);}

接口处理 headers设置 'Content-Type': 'multipart/form-data'

transformRequest: [function (data, headers) { const formData = new FormData() for (const key of Object.keys(data)) { if (data[key] || data[key] === '') { formData.append(key, data[key]) } } return formData}]

FileReader对象的readAsDataURL方法可以将读取到的文件编码成Data URL

let reader = new FileReader()let this_ = thisreader.onload = function(evt) {// 获取 image 的URL this_.imageUrl = evt.target.result; this_.searchPeople()}reader.readAsDataURL(event.target.files[0]); var renameFile = new File([原文件], 新文件名, 文件类型);
标签:
声明:无特别说明,转载请标明本文来源!
发布评论
正文 取消