javascript hapijs - API上传图片
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript hapijs - API上传图片相关的知识,希望对你有一定的参考价值。
server.route({
config: {
cors: {
origin: ['*'],
additionalHeaders: ['cache-control', 'x-requested-with']
}
},
method: 'POST',
path: '/attachments/upload',
config: {
payload: {
output: 'stream',
allow: 'multipart/form-data',
maxBytes: MAX_UPLOAD_SIZE * 1048576
}
},
handler: async (request, h) => {
try {
const data = request.payload;
const file = data['image'];
const fileOptions = { uploadDir, publicUploadPath };
// save the file
const { publicPath, originalName } = await uploader(file, fileOptions);
// return result
console(publicPath);
console.log(originalName);
return { publicPath, originalName };
} catch (err) {
return Boom.badRequest(err.message, err);
}
}
});
const cookies = Cookie.parse(document.cookie);
fetch('/api/attachments/upload', {
method: 'POST',
headers: {
'X-CSRF-Token': cookies.crumb
},
body
})
.then((res) => res.json())
.catch((error) => console.error('Error:', error));
const fs = require('fs');
const { join } = require('path');
const uuid = require('uuid');
module.exports = (file, { uploadDir, publicUploadPath, fileName }) => {
const originalName = file.hapi.filename;
// const filename = `${uuid.v1()}-${originalName}`;
const filename = fileName;
const path = join(uploadDir, filename);
const publicPath = join(publicUploadPath, filename);
const fileStream = fs.createWriteStream(path);
return new Promise((resolve, reject) => {
file.on('error', err => {
reject(err);
});
file.pipe(fileStream);
file.on('end', err => {
const fileDetails = {
fieldname: file.hapi.name,
originalName,
filename,
mimetype: file.hapi.headers['content-type'],
destination: uploadDir,
path,
publicPath,
size: fs.statSync(path).size,
}
resolve(fileDetails);
})
})
};
以上是关于javascript hapijs - API上传图片的主要内容,如果未能解决你的问题,请参考以下文章
CORS 问题,HapiJS HAPI-16
CORS 不适用于 hapijs 和 socket.io
如何将 PassportJS 与 HapiJS 一起使用
HapiJS 启动更长的后台进程
hapijs joi 验证,只验证一个字段并允许任何字段
如何使用HapiJs和MongoDB实现本地化