我正在进行下一个js项目,允许用户上传图像,我将图像存储在我的公共目录中,是否有任何方法可以使用URL结构(如www.example.com)访问我的文件mydomain.com/public/coverimg/image.jpg
下面是我的API代码。
import { rejects } from 'assert';
import { resolve } from 'path';
import { promises } from 'stream';
const fs = require('fs');
const moment = require('moment');
const formidable = require('formidable-serverless');
var slugify = require('slugify');
const path = require('path');
const crypto = require('crypto');
export const config = {
api: {
bodyParser: false,
},
};
const handler = async (req, res) => {
const timeStamp = moment().format('DD_MM_YYYY');
const Image_id = crypto.randomBytes(16).toString('hex');
fs.mkdir(
`./public/coverimg/${timeStamp}`,
{ recursive: true },
function (err) {
res.send(err);
}
);
const data = await new Promise((resolve, rejects) => {
const form = formidable({
multple: false,
uploadDir: `./public/coverimg/${timeStamp}`,
});
form.KeepExtentions = true;
form.KeepFileName = true;
form.maxFields = 1000;
form.on('fileBegin', function (name, file) {
file.path = path.join(
`./public/coverimg/${timeStamp}`,
Image_id + '_' + slugify(file.name)
);
});
// console.log(data);
form.parse(req, (error, fields, files) => {
if (error) return rejects(error);
resolve(files);
});
});
};
export default handler;
1条答案
按热度按时间wfsdck301#
您应该使用以下格式共享URL:
例如
注意:不要在您的共享URL中包含
/public/
。