这样写在回调里就ctx.body就没有了,直接在外面有返回
const {BosClient, MimeType} = require('bce-sdk-js')
const fs = require('fs')
const path = require('path')
function upload(ctx) {
const uploadFilePath = ctx.request.body.path;
const file = ctx.request.files.file;
// 创建可读流
const reader = fs.createReadStream(file.path);
let filePath = path.join('static/upload/') + `${file.name}`;
// 创建可写流
const upStream = fs.createWriteStream(filePath);
// 可读流通过管道写入可写流
reader.pipe(upStream);
const bucket = 'tp-statics';
const endpoint = 'xxx';
const config = {
endpoint, //传入Bucket所在区域域名
credentials: {
ak: 'xxx', // 您的AccessKey
sk: 'xxx' // 您的SecretAccessKey
}
};
const client = new BosClient(config);
// 上传路径+文件名
const key = uploadFilePath + file.name;
const ext = key.split(/\./g).pop();
// 检查类型
let mimeType = MimeType.guess(ext);
if (/^text\//.test(mimeType)) mimeType += '; charset=UTF-8';
const options = {
'Content-Type': mimeType
};
reader.on("close", () => {
// console.log("流关闭了~~~");
client.putObjectFromFile(bucket, key, filePath, options).then(res => {
ctx.body = {
code: 200,
data: {
domain: 'https://xxx',
key,
url: `https://xxx/${key}`
},
message: '上传成功'
}
}).catch(err => {
ctx.body = {
code: 500,
message: err
}
})
});
}