From 8b8ebe5e2ed1cd0036ff23651c7e44f24f693ec6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E6=99=93=E5=A3=AE?= <595819923@qq.com> Date: Sat, 20 Mar 2021 10:30:43 +0800 Subject: [PATCH] Update api_material.js MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 统一临时素材与永久素材的上传方法 --- lib/api_material.js | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/lib/api_material.js b/lib/api_material.js index a5151bc..117fcbe 100644 --- a/lib/api_material.js +++ b/lib/api_material.js @@ -25,13 +25,20 @@ const { postJSON } = require('./util'); * Shortcut: * - `exports.uploadImageMaterial(filepath);` * - `exports.uploadVoiceMaterial(filepath);` * - `exports.uploadThumbMaterial(filepath);` * @param {String} filepath 文件路径 - * @param {String} type 媒体类型,可用值有image、voice、video、thumb + * @param {String|Buffer} filepath 文件路径/文件Buffer数据 + * @param {String} type 媒体类型,可用值有image、voice、thumb + * @param {String} filename 文件名 + * @param {String} mime 文件类型,filepath为Buffer数据时才需要传 */ -exports.uploadMaterial = async function (filepath, type) { +exports.uploadMaterial = async function (filepath, type, filename, mime) { const { accessToken } = await this.ensureAccessToken(); - var stat = await statAsync(filepath); var form = formstream(); - form.file('media', filepath, path.basename(filepath), stat.size); + if (Buffer.isBuffer(filepath)) { + form.buffer('media', filepath, filename, mime); + } else if (typeof filepath === 'string') { + var stat = await statAsync(filepath); + form.file('media', filepath, filename || path.basename(filepath), stat.size); + } var url = this.prefix + 'material/add_material?access_token=' + accessToken + '&type=' + type; var opts = { dataType: 'json', @@ -42,11 +49,11 @@ exports.uploadMaterial = async function (filepath, type) { }; return this.request(url, opts); }; - + ['image', 'voice', 'thumb'].forEach(function (type) { var method = 'upload' + type[0].toUpperCase() + type.substring(1) + 'Material'; - exports[method] = async function (filepath) { - return this.uploadMaterial(filepath, type); + exports[method] = async function (filepath, filename, mime) { + return this.uploadMaterial(filepath, type, filename, mime); }; });