Upgrade img upld to all files! :D
This commit is contained in:
parent
d69b6bef0c
commit
d41547d31f
12 changed files with 185 additions and 146 deletions
|
|
@ -1,50 +1,54 @@
|
|||
import * as bodyParser from 'body-parser'
|
||||
import cors from 'cors'
|
||||
import express from 'express'
|
||||
import { existsSync, mkdirSync } from 'fs'
|
||||
import moment from 'moment-timezone'
|
||||
import multer from 'multer'
|
||||
import path from 'path'
|
||||
import { mw as requestIpMw } from 'request-ip'
|
||||
import getImageHandler from './app/controllers/img/getImageHandler'
|
||||
import putImageHandler from './app/controllers/img/putImageHandler'
|
||||
import getTxtHandler from './app/controllers/txt/getTxtHandler'
|
||||
import putTxtHandler from './app/controllers/txt/putTxtHandler'
|
||||
import getUrlHandler from './app/controllers/url/getUrlHandler'
|
||||
import putUrlHandler from './app/controllers/url/putUrlHandler'
|
||||
import * as bodyParser from "body-parser";
|
||||
import cors from "cors";
|
||||
import express from "express";
|
||||
import { existsSync, mkdirSync } from "fs";
|
||||
import moment from "moment-timezone";
|
||||
import multer from "multer";
|
||||
import { mw as requestIpMw } from "request-ip";
|
||||
import getFileHandler from "./app/controllers/file/getFileHandler";
|
||||
import putFileHandler from "./app/controllers/file/putFileHandler";
|
||||
import getTxtHandler from "./app/controllers/txt/getTxtHandler";
|
||||
import putTxtHandler from "./app/controllers/txt/putTxtHandler";
|
||||
import getUrlHandler from "./app/controllers/url/getUrlHandler";
|
||||
import putUrlHandler from "./app/controllers/url/putUrlHandler";
|
||||
|
||||
const app = express()
|
||||
const app = express();
|
||||
|
||||
app.use(cors())
|
||||
app.use(requestIpMw())
|
||||
app.use(bodyParser.json())
|
||||
app.use(bodyParser.urlencoded({
|
||||
extended: true
|
||||
}))
|
||||
app.use(cors());
|
||||
app.use(requestIpMw());
|
||||
app.use(bodyParser.json());
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
extended: true,
|
||||
})
|
||||
);
|
||||
|
||||
const uploadPath = '/tmp/ImgUploads'
|
||||
const uploadPath = "/tmp/FileUploads";
|
||||
if (!existsSync(uploadPath)) {
|
||||
mkdirSync(uploadPath)
|
||||
mkdirSync(uploadPath);
|
||||
}
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
cb(null, uploadPath)
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
cb(null, `${file.fieldname}-${moment().toISOString()}`)
|
||||
}
|
||||
})
|
||||
// 52428800 = 50mb
|
||||
const uploader = multer({ storage, limits: { fileSize: 52428800 } })
|
||||
// Image Uploader
|
||||
app.put("/api/img", uploader.single("image"), putImageHandler)
|
||||
app.get("/i/:slug", getImageHandler)
|
||||
// Pastebin
|
||||
app.put("/api/paste", putTxtHandler)
|
||||
app.get("/p/:slug", getTxtHandler)
|
||||
// URL Shortener -- LAST for a reason.
|
||||
app.put("/api/url", putUrlHandler)
|
||||
app.get("/:slug", getUrlHandler)
|
||||
destination: (req, file, cb) => {
|
||||
cb(null, uploadPath);
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
cb(null, `${file.fieldname}-${moment().toISOString()}`);
|
||||
},
|
||||
});
|
||||
|
||||
export default app
|
||||
const uploader = multer({
|
||||
storage,
|
||||
// limits: { fileSize: 17825792 },
|
||||
}).single("file");
|
||||
// Image Uploader
|
||||
app.put("/api/file", uploader, putFileHandler);
|
||||
app.get("/f/:slug", getFileHandler);
|
||||
// Pastebin
|
||||
app.put("/api/paste", putTxtHandler);
|
||||
app.get("/p/:slug", getTxtHandler);
|
||||
// URL Shortener -- LAST for a reason.
|
||||
app.put("/api/url", putUrlHandler);
|
||||
app.get("/:slug", getUrlHandler);
|
||||
|
||||
export default app;
|
||||
|
|
|
|||
28
backend/src/app/controllers/file/getFileHandler.ts
Normal file
28
backend/src/app/controllers/file/getFileHandler.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { Request, Response } from "express";
|
||||
import Files from "../../db/file.schema";
|
||||
|
||||
export default async (req: Request, res: Response) => {
|
||||
try {
|
||||
const file = await Files.findById(req.params.slug);
|
||||
|
||||
if (file) {
|
||||
// If it's an image, render it instead of DLing it
|
||||
const isImage = file.img.contentType.startsWith("image/");
|
||||
|
||||
res.setHeader(
|
||||
"Content-Disposition",
|
||||
`${isImage ? "" : "attachment;"} filename=${file.img.name}`
|
||||
);
|
||||
res.contentType(file.img.contentType);
|
||||
return res.send(file.img.data);
|
||||
} else {
|
||||
console.log("did not find file");
|
||||
res.status(404).end();
|
||||
}
|
||||
} catch (ex) {
|
||||
console.error(ex);
|
||||
return res.status(500).send({
|
||||
error: ex,
|
||||
});
|
||||
}
|
||||
};
|
||||
36
backend/src/app/controllers/file/putFileHandler.ts
Normal file
36
backend/src/app/controllers/file/putFileHandler.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { Request, Response } from "express";
|
||||
import fs from "fs";
|
||||
import Files from "../../db/file.schema";
|
||||
|
||||
export default async (req: Request, res: Response) => {
|
||||
try {
|
||||
const data = fs.readFileSync(req.file.path);
|
||||
fs.unlinkSync(req.file.path);
|
||||
|
||||
const files = await Files.find();
|
||||
|
||||
for (const file of files) {
|
||||
if (file.img.data.compare(data) === 0) {
|
||||
/* If some other IP uploads, we want to add them too */
|
||||
file.uploaders.push(req.clientIp as string);
|
||||
await file.save();
|
||||
return res.status(200).send(file._id);
|
||||
}
|
||||
}
|
||||
|
||||
const file = new Files();
|
||||
|
||||
file.img.contentType = req.file.mimetype;
|
||||
file.img.name = req.file.originalname;
|
||||
file.img.data = data;
|
||||
file.uploaders = req.clientIp ? [req.clientIp as string] : [];
|
||||
|
||||
await file.save();
|
||||
|
||||
return res.status(200).send(file._id);
|
||||
} catch (ex) {
|
||||
return res.status(500).send({
|
||||
error: ex,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
import { Request, Response } from 'express'
|
||||
import Images from '../../db/img.schema'
|
||||
|
||||
export default async (req: Request, res: Response) => {
|
||||
try {
|
||||
const img = await Images.findById(req.params.slug)
|
||||
|
||||
if (img) {
|
||||
res.contentType(img.img.contentType)
|
||||
res.send(img.img.data)
|
||||
} else {
|
||||
res.status(404).end()
|
||||
}
|
||||
} catch (ex) {
|
||||
console.error(ex)
|
||||
return res.status(500).send({
|
||||
error: ex
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
import { Request, Response } from 'express'
|
||||
import fs from 'fs'
|
||||
import Images from '../../db/img.schema'
|
||||
|
||||
export default async (req: Request, res: Response) => {
|
||||
try {
|
||||
const data = fs.readFileSync(req.file.path)
|
||||
fs.unlinkSync(req.file.path)
|
||||
|
||||
const images = await Images.find()
|
||||
|
||||
for (const img of images) {
|
||||
if (img.img.data.compare(data) === 0) {
|
||||
/* If some other IP uploads, we want to add them too */
|
||||
img.uploaders.push(req.clientIp as string)
|
||||
await img.save()
|
||||
return res.status(200).send(img._id)
|
||||
}
|
||||
}
|
||||
|
||||
const img = new Images()
|
||||
|
||||
img.img.contentType = req.file.mimetype
|
||||
img.img.data = data
|
||||
img.uploaders = req.clientIp ? [req.clientIp as string] : []
|
||||
|
||||
await img.save()
|
||||
|
||||
return res.status(200).send(img._id)
|
||||
} catch (ex) {
|
||||
console.error(ex)
|
||||
return res.status(500).send({
|
||||
error: ex
|
||||
})
|
||||
}
|
||||
}
|
||||
34
backend/src/app/db/file.schema.ts
Normal file
34
backend/src/app/db/file.schema.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import moment from "moment";
|
||||
import { Document, model, Schema } from "mongoose";
|
||||
import shortid from "shortid";
|
||||
|
||||
const FileSchema = new Schema({
|
||||
_id: {
|
||||
type: String,
|
||||
default: shortid.generate,
|
||||
},
|
||||
createdAt: {
|
||||
type: Date,
|
||||
default: moment().toISOString(),
|
||||
},
|
||||
uploaders: [String],
|
||||
img: {
|
||||
contentType: String,
|
||||
data: Buffer,
|
||||
name: String,
|
||||
},
|
||||
});
|
||||
|
||||
export type FileModel = Document & {
|
||||
_id: string;
|
||||
createdAt: Date;
|
||||
uploaders: string[];
|
||||
img: {
|
||||
contentType: string;
|
||||
data: Buffer;
|
||||
name: string;
|
||||
};
|
||||
};
|
||||
|
||||
// Left this as images to retain old data
|
||||
export default model<FileModel>("images", FileSchema, "images");
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
import moment from 'moment'
|
||||
import { Document, model, Schema } from 'mongoose'
|
||||
import shortid from 'shortid'
|
||||
|
||||
const ImgSchema = new Schema({
|
||||
_id: {
|
||||
type: String,
|
||||
default: shortid.generate
|
||||
},
|
||||
createdAt: {
|
||||
type: Date,
|
||||
default: moment().toISOString()
|
||||
},
|
||||
uploaders: [String],
|
||||
img: {
|
||||
contentType: String,
|
||||
data: Buffer,
|
||||
}
|
||||
})
|
||||
|
||||
export type ImgModel = Document & {
|
||||
_id: string,
|
||||
createdAt: Date,
|
||||
uploaders: string[],
|
||||
img: {
|
||||
contentType: string,
|
||||
data: Buffer
|
||||
}
|
||||
}
|
||||
|
||||
export default model<ImgModel>("images", ImgSchema, "images")
|
||||
|
|
@ -2,10 +2,10 @@ import 'bootstrap/dist/css/bootstrap.min.css';
|
|||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { BrowserRouter as Router, Route } from 'react-router-dom';
|
||||
import FileUpload from './components/FileUpload';
|
||||
import NavBar from './components/modules/NavBar';
|
||||
import UrlShortener from './components/UrlShortener';
|
||||
import ImageUpload from './components/ImageUpload';
|
||||
import TextUpload from './components/TextUpload';
|
||||
import UrlShortener from './components/UrlShortener';
|
||||
|
||||
export default () => {
|
||||
ReactDOM.render(
|
||||
|
|
@ -14,7 +14,7 @@ export default () => {
|
|||
<NavBar />
|
||||
<div style={{ paddingTop: `${3.5}em` }} />
|
||||
<Route exact path="/" component={UrlShortener} />
|
||||
<Route exact path="/i" component={ImageUpload} />
|
||||
<Route exact path="/f" component={FileUpload} />
|
||||
<Route exact path="/p" component={TextUpload} />
|
||||
</Router>
|
||||
</React.StrictMode>,
|
||||
|
|
|
|||
13
frontend/src/axios/putFileHandler.js
Normal file
13
frontend/src/axios/putFileHandler.js
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import axios from 'axios';
|
||||
|
||||
export default (file) => {
|
||||
if (file.size > 16000000) {
|
||||
return { error: true, size: file.size };
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
return axios.put('/api/file', formData)
|
||||
.then((resp) => resp.data)
|
||||
.catch((ex) => alert(ex));
|
||||
};
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
import axios from 'axios';
|
||||
|
||||
export default (file) => {
|
||||
const formData = new FormData();
|
||||
formData.append('image', file);
|
||||
return axios.put('/api/img', formData).then((resp) => resp.data);
|
||||
};
|
||||
|
|
@ -3,24 +3,37 @@ import {
|
|||
Button, Container, Form, InputGroup,
|
||||
} from 'react-bootstrap';
|
||||
import { CSSTransition } from 'react-transition-group';
|
||||
import putImgHandler from '../axios/putImgHandler';
|
||||
import putImgHandler from '../axios/putFileHandler';
|
||||
|
||||
const toMb = (size) => (size / 1000000).toFixed(2);
|
||||
|
||||
export default () => {
|
||||
const [state, setState] = useState({
|
||||
loading: false,
|
||||
result: null,
|
||||
file: null,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const submit = (evt) => {
|
||||
evt.preventDefault();
|
||||
if (state.file && state.file.name.length) {
|
||||
if (state.file.size > 16000000) {
|
||||
setState({
|
||||
loading: false,
|
||||
result: null,
|
||||
file: null,
|
||||
error: `File size ${toMb(state.file.size)}MB is too large`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setState({ ...state, loading: true });
|
||||
putImgHandler(state.file).then((data) => {
|
||||
setState({
|
||||
...state,
|
||||
result: `http://${window.location.host}/i/${data}`.replace('5000', '3000'),
|
||||
loading: false,
|
||||
result: `${window.location.origin}/f/${data}`.replace('5000', '3000'),
|
||||
file: null,
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
@ -29,7 +42,7 @@ export default () => {
|
|||
return (
|
||||
<CSSTransition classNames="react-router" appear in timeout={300}>
|
||||
<Container className="perfect-width">
|
||||
<h2 className="text-center mt-10 py-3">Image Uploader</h2>
|
||||
<h2 className="text-center mt-10 py-3">File Uploader</h2>
|
||||
|
||||
<Form onSubmit={submit} className="perfect-width">
|
||||
<Form.Group>
|
||||
|
|
@ -37,9 +50,8 @@ export default () => {
|
|||
<Form.File
|
||||
custom
|
||||
required
|
||||
id="image"
|
||||
accept="image/*"
|
||||
label={(state.file && state.file.name) || 'Select Image (Max: 50MB)'}
|
||||
accept="*"
|
||||
label={(state.file && state.file.name) || 'Select File (Max: 16MB)'}
|
||||
onChange={(evt) => setState({ ...state, file: evt.target.files[0] })}
|
||||
/>
|
||||
<InputGroup.Append>
|
||||
|
|
@ -51,6 +63,12 @@ export default () => {
|
|||
</Form.Group>
|
||||
</Form>
|
||||
|
||||
{state.error && (
|
||||
<h5 className="text-center text-danger">
|
||||
{state.error}
|
||||
</h5>
|
||||
)}
|
||||
|
||||
{state.result && (
|
||||
<h5 className="text-center">
|
||||
<a rel="noopener noreferrer" href={state.result} target="_blank">
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { faCode, faImage, faLink } from '@fortawesome/free-solid-svg-icons';
|
||||
import { faCode, faFile, faLink } from '@fortawesome/free-solid-svg-icons';
|
||||
import React from 'react';
|
||||
import { Nav, Navbar } from 'react-bootstrap';
|
||||
import NavLinkItem from './NavLinkItem';
|
||||
|
|
@ -10,8 +10,8 @@ export default () => (
|
|||
<Navbar.Collapse>
|
||||
<Nav className="mr-auto">
|
||||
<NavLinkItem name="URL" dest="/" icon={faLink} />
|
||||
<NavLinkItem name="Paste" dest="/p" icon={faCode} />
|
||||
<NavLinkItem name="Img" dest="/i" icon={faImage} />
|
||||
<NavLinkItem name="Code" dest="/p" icon={faCode} />
|
||||
<NavLinkItem name="File" dest="/f" icon={faFile} />
|
||||
</Nav>
|
||||
</Navbar.Collapse>
|
||||
</Navbar>
|
||||
|
|
|
|||
Loading…
Reference in a new issue