关于如何发送 REST 请求,我说我们没有 REST 请求,REST 只是一种接受 get、post、put、del 请求的设计。所以你可以在没有 RESTful 设计的情况下工作
您可以使用此package,该package 已针对上传文件进行了优化。
首先使用 multer 定义一个上传助手:
const multer = require('multer');
const mkdirp = require('mkdirp');
const fs = require('fs');
const getDirImage = () => {
let year = new Date().getFullYear();
let month = new Date().getMonth() + 1;
let day = new Date().getDay();
return `${config.homedir}/public_html/uploads/images/${year}/${month}/${day}`;
};
const ImageStorage = multer.diskStorage({
destination: (req, file, cb) => {
let dir;
if (file.mimetype === 'text/css') {
dir = getDirCss();
} else {
dir = getDirImage();
}
mkdirp(dir, (err) => cb(null, dir))
},
filename: (req, file, cb) => {
let filePath;
if (file.mimetype === 'text/css') {
filePath = getDirCss() + '/' + file.originalname;
} else {
filePath = getDirImage() + '/' + file.originalname;
}
if (!fs.existsSync(filePath))
cb(null, file.originalname);
else
cb(null, Date.now() + '-' + file.originalname);
}
});
const uploadImage = multer({
storage: ImageStorage,
limits: {
fileSize: 1024 * 1024 * 10
}
});
module.exports = uploadImage;
在您的路线文件中:
const upload = require('path/to/upload/helper');
router.post('/imageUpload', upload.single('image'), imageValidator.handle(), imageController.update);
然后你可以在req.file访问你上传的文件
关于将 iamge 返回给用户,您可以在上传文件夹中返回其 url,以便他们获取;但为此,您需要提供静态文件:
app.use(express.static('your_upload_dir'));
现在您可以在以下位置访问静态文件:
your_url/file's_location
或:localhost:your_app_port/file's location
如果你在 localhost 上进行测试
如果您想限制对这些文件的访问,您可以使用中间件来检查用户的令牌或 IP 或其他内容。困难的部分是创建一个模型来存储文件名和 url 以及一个通过文件名请求文件的路径。