Skip to content

Commit

Permalink
feature: core 文件操作 uploadFileAndSend.js to #31
Browse files Browse the repository at this point in the history
  • Loading branch information
Drincann committed Apr 12, 2021
1 parent 375a136 commit 977bd85
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/core/uploadFileAndSend.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const { errCodeMap } = require('../util/errCode');
const axios = require('axios').default;
let URL;
if (!process.browser) {
({ URL } = require('url'));
} else {
URL = window.URL;
}
const errorHandler = require('../util/errorHandler');
const FormData = require('form-data');


/**
* @description 上传文件至服务器并发送,返回文件 id
* @param {string} baseUrl mirai-api-http server 的地址
* @param {string} sessionKey 会话标识
* @param {string} type "friend" 或 "group",目前仅支持 group
* @param {string} path 上传目录
* @param {Buffer} file 文件二进制数据
* @returns {string} 文件 id
*/
module.exports = async ({ baseUrl, sessionKey, type, path, file }) => {
try {
// 拼接 url
const targetUrl = new URL('/uploadFileAndSend', baseUrl).toString();

// 构造 fromdata
const form = new FormData();
form.append('sessionKey', sessionKey);
form.append('type', type);
form.append('path', path);
form.append('file', file);

// 请求
const responseData = await axios.post(targetUrl, form, {
// formdata.getHeaders 将会指定 content-type,同时给定随
// 机生成的 boundary,即分隔符,用以分隔多个表单项而不会造成混乱
headers: form.getHeaders(),
});

try {
var {
data: { msg: message, code, id }
} = responseData;
} catch (error) {
throw new Error('core.uploadFileAndSend 请求返回格式出错,请检查 mirai-console');
}

// 抛出 mirai 的异常,到 catch 中处理后再抛出
if (code in errCodeMap) {
throw new Error(message);
}
return id;
} catch (error) {
errorHandler(error);
}
};

1 comment on commit 977bd85

@vercel
Copy link

@vercel vercel bot commented on 977bd85 Apr 12, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.