Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const bodyParser = require('body-parser');
- const fileType = require('file-type');
- const fs = require('fs');
- const shortid = require('shortid');
- const cfg = require('./config.json')
- const app = express();
- app.use(bodyParser.raw({
- type: 'image/png',
- limit: '20mb'
- }));
- app.use(bodyParser.raw({
- type: 'image/jpeg',
- limit: '20mb'
- }));
- app.use(bodyParser.raw({
- type: 'image/gif',
- limit: '20mb'
- }));
- const getTimestamp = () => {
- const dt = new Date;
- return `[${
- dt.getDate().toString().padStart(2, '0')}.${
- (dt.getMonth()+1).toString().padStart(2, '0')}.${
- dt.getFullYear().toString().padStart(4, '0')} ${
- dt.getHours().toString().padStart(2, '0')}:${
- dt.getMinutes().toString().padStart(2, '0')}:${
- dt.getSeconds().toString().padStart(2, '0')}]`
- }
- const cd = new Set();
- app.post('/push', async (req, res) => {
- const ip = req.headers['x-forwarded-for'] || req.ip;
- if(cd.has(ip)){
- return res.status(429).json({ok: false, error: 'Вы отправляете слишком много запросов'})
- }
- cd.add(ip);
- setTimeout(() => {
- cd.delete(ip);
- }, 5000);
- try{
- const buf = Buffer.from(req.body);
- const mimeInfo = await fileType.fromBuffer(buf);
- if(['image/png', 'image/jpeg', 'image/gif'].includes(mimeInfo.mime)){
- const id = shortid.generate();
- fs.writeFileSync('./storage/' + id, but);
- console.log(getTimestamp(), 'Uploaded new image -> ' + id);
- res.json({ok: true, data: {id}});
- }
- else{
- res.status(400).json({ok: false, error: 'Неверный тип файла'})
- }
- }
- catch(err){
- res.status(500).json({ok: false, error: 'В процессе загрузки произошла неизвестная ошибка'})
- console.error(getTimestamp(), err);
- }
- })
- app.get('/:id', async (req, res) => {
- if(fs.existsSync('./storage/' + req.params.id)){
- res.sendFile('./storage/' + req.params.id);
- }
- else res.status(404).send();
- })
- app.listen(cfg.port);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement