vue + node如何通过一个Txt文件批量生成MP3并压缩成Zip

2020-06-16 06:59:15易采站长站整理

看看效果叭

解压的文件

上传的文件格式

测试1|||测试1的文字
测试2|||测试2的文字
测试3|||测试3的文字
测试4|||测试4的文字
测试5|||测试5的文字

实现的逻辑如下

上传文件
解析txt
发送内容至百度语音合成
生成文件夹放置本次合成的mp3文件,并压缩成zip
发送zip的地址给前端

使用了 element-ui 的 el-upload 组件


<el-upload
v-loading="loading"
class="upload-demo"
drag
ref="upload"
action="#"
accept=".txt"
:before-upload="onBeforeUploadImage"
:http-request="UploadImage"
:on-change="fileChange"
:file-list="fileList"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或
<em>点击上传</em>
</div>
<div class="el-upload__tip" slot="tip">只能上传txt文件,且不超过1M</div>
</el-upload>

在上传之前判断上传的文件是否符合要求


onBeforeUploadImage(file) {
const isTxt = file.type === "text/plain";
const isLt1M = file.size / 1024 / 1024 < 1;
if (!isTxt) {
this.$message.error("上传文件只能是txt格式!");
}
if (!isLt1M) {
this.$message.error("上传文件大小不能超过 1MB!");
}
return isTxt && isLt1M;
}

一次只上传一个文件,在文件列表更新时先清除之前的文件


fileChange(file) {
let obj = this.onBeforeUploadImage(file.raw);
if (obj) {
this.$refs.upload.clearFiles();
this.fileList = [{ name: file.name, url: file.url }];
}
}

上传的主要函数


UploadImage(param) {
this.loading = true;
const formData = new FormData();
formData.append("file", param.file);
this.$axios({
url: process.env.VUE_APP_BASE_API + "api/txtToMp3",
method: "post",
data: formData
})
.then(response => {
if (response.data.code == 0) {
this.loading = false;
this.dialogVisible = true;
this.url = response.data.data.url;
}
})
.catch(error => {
console.log(error);
});
}

node代码

用到的依赖项


const formidable = require("formidable"); //获取上传的txt,并保存
const path = require("path");
const AipSpeech = require("baidu-aip-sdk").speech; //百度语音合成sdk