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); }; });