How to use multer - 10 common examples

To help you get started, we’ve selected a few multer examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github yanatan16 / nanoajax / test / server.js View on Github external
function corsify(req, res) {
  // IE 6-7 requires this P3P header
  res.setHeader('P3P', 'CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"')

  // Standards-compatible CORS headers
  res.setHeader('Access-Control-Allow-Origin', req.get('origin') || '*')
  res.setHeader('Access-Control-Allow-Credentials', true)

  res.setHeader('Cache-Control', 'no-cache')
}

app.use(require('morgan')('dev'))
app.use(require('body-parser').urlencoded({extended:false}))
app.use(require('body-parser').json())
app.use(require('cookie-parser')())
app.use(require('multer')({ dest: 'temp/ '}).any())

app.get('/nanoajax.min.js', function (req, res) {
  fs.createReadStream(__dirname + '/../nanoajax.min.js', {encoding:'utf8'})
    .pipe(res)
})

app.get('/get', function (req, res) {
  res.send('OK')
})

app.post('/post', function (req, res) {
  if (req.body.arg === 'value' && req.body.foo === 'bar')
    res.send('OK')
  else
    res.status(400).send('Bad Request: ' + JSON.stringify(req.body))
})
github giper45 / DockerSecurityPlayground / index.js View on Github external
const repoHandler = require('./app/handlers/repos');
const dockerImages = require('./app/handlers/docker-images');
const serviceHandler = require('./app/handlers/services')
const dockerfilesHandler = require('./app/handlers/dockerfiles')
// const installationHandler = require('./app/handlers/installation.js');
const treeRoutes = require('./app/handlers/tree_routes.js');
const Checker = require('./app/util/AppChecker.js');
const multer = require('multer');
const webSocketHandler = require('./app/util/ws_handler.js');
const localConfig = require('./config/local.config.json');
const healthChecker = require('./app/util/HealthLabState.js');
const errorHandler = require('express-error-handler');

const port = +process.env.PORT || 8080;
// var upload = multer({ dest: "uploads/" });
const storage = multer.memoryStorage();
const upload = multer({ storage });
const server = http.createServer(app);
const AppUtils = require('./app/util/AppUtils.js');
const dockerSocket = require('./app/util/docker_socket');

// const webshellConfigFile =
const log = AppUtils.getLogger();
// Initialize the checker
Checker.init((err) => {
  if (err) {
    console.error(err.message);
    throw err;
  }
});
// If is installed start the healtChecker
Checker.isInstalled((isInstalled) => {
github cdimascio / express-openapi-validator / src / middlewares / openapi.multipart.ts View on Github external
function error(req, err) {
  if (err instanceof multer.MulterError) {
    // TODO is special handling for MulterErrors needed
    console.error(err);
    return validationError(500, req.path, err.message);
  } else {
    // HACK
    // TODO improve multer error handling
    const missingField = /Multipart: Boundary not found/i.test(
      err.message || '',
    );
    if (missingField) {
      return validationError(400, req.path, 'multipart file(s) required');
    } else {
      console.error(err);
      return validationError(500, req.path, err.message);
    }
  }
github jupyter-attic / dashboards_server / app / upload-notebook.js View on Github external
// check for *.ipynb extension
    if (/\.ipynb$/.test(file.originalname)) {
        cb(null, true);
    } else {
        cb(new Error('Wrong file extension. Make sure to upload a Jupyter Notebook file (*.ipynb).'));
    }
}

var limits = {
    fields: 0,
    files: 1,
    parts: 1
};

// Use multer disk storage to write uploaded file
var storage = multer.diskStorage({
    destination: destination,
    filename: filename
});
module.exports = multer({
    storage: storage,
    fileFilter: fileFilter,
    limits: limits
});
github PAN001 / QuickNote / app.js View on Github external
console.log(req.body.email);
    // move
    var destPath = '/root/Public/QuickNote/public/cloud/'+req.body.email+'/'+videoName;
    var relPath = '/cloud/'+req.body.email+'/'+videoName;
    fs.rename(tmpPath+videoName,destPath, function(err){
        if(err){
            throw err;
        }
    });
    res.json({code: 200, path: relPath});


});

var audioName;
var audioStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, tmpPath);
    },
    filename: function (req, file, cb) {
        var date = new Date();
        audioName  = "Audio-Recording-"+date.format("yyyy-MM-dd-hh-mm-ss")+".wav";
        cb(null, audioName);
    }
});
var audioUpload = multer({storage: audioStorage});

app.post("/uploadAudio", audioUpload.any(), function(req, res) {
    console.log("audio upload received");
    // move
    var destPath = '/root/Public/QuickNote/public/cloud/'+req.body.email+'/'+audioName;
    var relPath = '/cloud/'+req.body.email+'/'+audioName;
github ThalKod / discord-clone / routes / channel.js View on Github external
const   express     = require("express");
const   { ObjectID } = require("mongodb");
const   moment      = require("moment");
const   multer      = require("multer");
const   mime        = require("mime-types");
const   path        = require("path");
const   crypto      = require("crypto");
const   User        = require("../models/user");
const   middleware  = require("../middleware/index");
const   Channel     = require("../models/channel");

const       router = express.Router();

const upload = multer({
    storage: multer.diskStorage({
        destination: path.join(__dirname, "../public/files/image"),
        filename: (req, file, cb)=>{
            crypto.pseudoRandomBytes(4, (err, raw)=>{
                const mimeType = mime.lookup(file.originalname);
                // throw away any extension if provided
                const nameSplit = file.originalname.split(".").slice(0, -1);
                // nameSplit.pop();

                // replace all white spaces with - for safe file name on different filesystem
                const name = nameSplit.join(".").replace(/\s/g, "-");
                cb(null, raw.toString("hex") + name + "." + mime.extension(mimeType));
            });
        },
    }),
});
github Pathgather / smashgather / server / server / production.js View on Github external
import jwt from "jsonwebtoken"
import multer from 'multer'

const JWT_SECRET = process.env.JWT_SECRET
if (!JWT_SECRET) {
  throw new Error("JWT_SECRET environment variable undefined!")
}

let app = express()

app.set("port", (process.env.PORT || 3000))

// Expose a GraphQL endpoint
app.use(expressJwt({ secret: JWT_SECRET, credentialsRequired: false }))
app.use(compression())
app.use("/graphql", multer({ storage: multer.memoryStorage() }).single('screenshot'))
app.use("/graphql", graphQLHTTP( request => ({
  graphiql: true,
  pretty: true,
  schema: Schema,
  rootValue: {
    user: request.user,
    request: request
  },
})))

// Serve static resources
app.use("/", express.static(path.resolve(__dirname, "../public")))
app.listen(app.get("port"), () => {
  console.log("Smashgather App is now running on port", app.get("port"))

  // Log a valid JWT, so that anyone who has access to server logs can execute mutations :)
github team-blockon / blockon / blockon-backend / routes / api / identity / identity.controller.js View on Github external
exports.uploadIdentity = async (req, res) => {
  const { accountAddress } = req.body;
  // const ethAddress = 'abcdefaad1daaaa'; //테스트용
  const upload = multer({
    storage: multer.memoryStorage(),
    fileFilter: async (req, file, cb) => {
      // cb(null, FileTypeCheck.uploadFileType(file.mimetype, imageType));
      cb(null, true);
    }
  }).single('identity'); // req.file은 identity 필드의 파일 정보

  /**
   * ipfs에 저장하고 db에 해쉬값을 저장한다.
   * @param file
   * @returns {Promise}
   */
  const saveToIPFS = async file => {
    console.log(file);
    const files = [
      {
        path: 'identity/' + file.originalname, //파일 이름을 유지하기위해 디렉토리 유지
github nax3t / image_upload_example / routes / campgrounds.js View on Github external
var express = require("express");
var router  = express.Router();
var Campground = require("../models/campground");
var middleware = require("../middleware");
var request = require("request");
var multer = require('multer');
var storage = multer.diskStorage({
  filename: function(req, file, callback) {
    callback(null, Date.now() + file.originalname);
  }
});
var imageFilter = function (req, file, cb) {
    // accept image files only
    if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) {
        return cb(new Error('Only image files are allowed!'), false);
    }
    cb(null, true);
};
var upload = multer({ storage: storage, fileFilter: imageFilter})

var cloudinary = require('cloudinary');
cloudinary.config({ 
  cloud_name: 'learntocodeinfo',
github tubackkhoa / tkframework / server / routes / graphql.js View on Github external
// field name => max count
const fieldMaxcountOptions = {
  'avatar': 1,
  'images': 10,
  'full_src': 1,
}

// extend here
const fieldOptions = Object.keys(fieldMaxcountOptions).map(name => ({
  name,
  maxCount: fieldMaxcountOptions[name]
}))

// only allow upload one by one ?
const multerMiddleware = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 1024 * 1024 }, // 1m
}).fields(fieldOptions)

const uploadMiddleWare = (req, res, next) => {
  multerMiddleware(req, res, () => {

    const names = req.files ? Object.keys(req.files) : null
    if (!names || names.length === 0) {
      return next()      
    }

    // Parse variables so we can add to them. (express-graphql won't parse them again once populated)
    // json paser will run later
    req.body.variables = JSON.parse(req.body.variables)
    names.forEach(name => {

multer

Middleware for handling `multipart/form-data`.

MIT
Latest version published 2 years ago

Package Health Score

74 / 100
Full package analysis