Archives
Trending
Support
Login
clear text
XML
Django
JavaScript
MATLAB
C
C++
C#
Python
SQL
Shell
Bash
Markdown
YAML
JSON
HTML
CSS
PHP
Java
Ruby
Go
Rust
Swift
Kotlin
Arduino
TypeScript
Perl
Autohotkey
Lua
SQF
R
Scala
Haskell
Groovy
Dart
Clojure
VB.NET
Objective-C
PowerShell
Bash
CoffeeScript
Verilog
function generateImgName(file_name) { const name = file_name.substring(0, file_name.lastIndexOf('.')) const ext = file_name.substring(file_name.lastIndexOf('.') + 1) return `${name}_${Date.now()}.${ext}` } function generateImgPath(name) { return `${__dirname}/../../client/public/uploads/${name}` } function resizeAndSave(img, path) { sharp(img.data).resize(400, 300, {fit: 'fill'}) .toFile(path) } function preprocessImage(req) { try { // CASE 1: Multi file upload req.files.file.forEach(img => { // Preprocess String to get image name and extension name = generateImgName(img.name) path = generateImgPath(name) // Push preprocessed image name to body before storing it to database req.body['images'].push({ name: name, path: `/uploads/${name}` }) // Resize image to 250 x 180 and save it resizeAndSave(img, path) }) } catch(err) { // CASE 2: Single file upload img = req.files.file name = generateImgName(img.name) path = generateImgPath(name) req.body['images'].push({ name: name, path: `/uploads/${name}` }) resizeAndSave(img, path) } } router.post('/add', async (req, res) => { // Reverse JSON.stringify() req.body.specifications = JSON.parse(req.body.specifications) req.body['images'] = [] preprocessImage(req) const newProduct = new Product(req.body) try { const ProductItem = await newProduct.save() if(!ProductItem) { throw new Error('Fail to save product..') } res.status(200).json(ProductItem) } catch(err) { res.status(500).json({message: err.message}) } })
Mark as private (unlisted)
for 30 minutes
for 6 hours
for 1 day
for 1 week
for 1 month
for 1 year
everlasting (like CCCP)