html代码:
<el-upload :action="addForm.path" v-model="addForm.path" class="avatar-uploader" :http-request="fileUploadHandler" :multiple="false" :before-upload="beforeAvatarUpload"> <el-button size="small" type="primary">点击上传</el-button> </el-upload>
js代码:
// 处理上传音频 async fileUploadHandler(event) { var that = this this.uploadLoading = true const { file } = event const formData = new FormData() formData.append(‘file‘, file) formData.append(‘path‘, ‘upload/audio‘) console.log(formData) try { let res = await axios.post(`/ui/core/file/upload`, formData, { headers: { ‘Content-Type‘: ‘multipart/form-data‘ } }) this.uploadLoading = false console.log(res) if (res.data.status === 1) { that.addForm.path = ‘存储路径‘ + file.name } else { this.$message.error(‘上传失败,请稍后再试下!‘) } } catch (e) { this.uploadLoading = false } },
还可以获取音频的大小和时间长度
html代码:
<el-upload id="audioUpload" class="avatar-uploader" :action="upLoadAudio" :show-file-list="true" :multiple="false" :file-list="fileList" :on-remove="handleRemove" :limit="1" :auto-upload="true" :on-change="handleChangeAudio" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <div slot="tip" class="el-upload__tip" style="margin-bottom: 10px"> 只能上传mp3文件,且不超过2M,播放长度不超过60s </div> </el-upload>
js代码:
beforeAvatarUpload(file) { // 文件类型进行判断 const isAudio = file.type === "audio/mp3" || file.type === "audio/mpeg"; // 限制上传文件大小 2M const isLt2M = file.size / 1024 / 1024 < 2; const isTime60S = this.audioDuration >= 60 ? true : ‘‘; // 获取时长 this.getTimes(file); if (!isAudio) { this.$message.error("上传文件只能是Mp3格式!"); this.fileList = []; } else { if (!isLt2M) { this.$message.error("上传文件大小不能超过 2MB!"); this.fileList = []; } else { if (!isTime60S) { this.$message.error("上传文件时长不能超过60秒!"); this.fileList = []; } } } return isAudio && isLt2M && isTime60S }, getTimes(file) { var content = file; //获取录音时长 var url = URL.createObjectURL(content); //经测试,发现audio也可获取视频的时长 var audioElement = new Audio(url); audioElement.addEventListener("loadedmetadata", (_event) => { this.audioDuration = parseInt(audioElement.duration); // console.log(this.audioDuration); }); },