How to use the multer function in multer

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 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 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 => {
github eden-js / cli / lib / eden / router.ts View on Github external
// create express app
    await eden.hook('eden.server.create', this.server);

    // Listen to port
    this.server.listen(eden.port, eden.host);

    // Log built to debug
    eden.logger.log('debug', `[${eden.port}] [${eden.host}] server listening`, {
      class : 'EdenRouter',
    });

    // Set server event handlers
    this.server.on('error', this.__error);

    // Set multer
    this.multer = multer(config.get('upload') || {
      dest : '/tmp',
    });

    // Loop HTTP request types
    ['use', 'get', 'post', 'push', 'delete', 'all'].forEach((type) => {
      // Create HTTP request method
      this[type] = (...typeArgs) => {
        // Call express HTTP request method
        this.app[type](...typeArgs);
      };
    });

    // Set express build methods
    const methods = ['_default', '_api', '_view', '_router', '_error'];

    // Loop methods
github recruit-tech / redux-pluto / src / shared / redux / __tests__ / lib / serverUtils.ts View on Github external
export default function createFileUploadServer(config) {
  const app = express();
  const upload = multer({ dest: path.resolve(__dirname, os.tmpdir()) });
  const server = (http.Server as any)(app);
  app.post(config.path, upload.single(config.fieldName), (req, res, next) => {
    res.send(req.file);
  });

  return server;
}
github devconcept / multer-gridfs-storage / test / legacy-mongo.spec.js View on Github external
function createStorageAndUpload(t, opts = {}) {
	const {url} = storageOpts();
	const storage = new GridFsStorage({url, ...opts});
	t.context.storage = storage;
	storage._legacy = true;
	t.context.upload = multer({storage});
}
github devconcept / multer-gridfs-storage / test / generator-promises.spec.js View on Github external
async function successfulPromiseSetup(t) {
	const app = express();
	t.context.filePrefix = 'file';
	const storage = new GridFsStorage({
		...storageOpts(),
		*file() {
			let counter = 0;
			for (;;) {
				yield Promise.resolve({filename: t.context.filePrefix + (counter + 1)});
				counter++;
			}
		}
	});
	t.context.storage = storage;

	const upload = multer({storage});

	app.post('/url', upload.array('photos', 2), (req, res) => {
		t.context.result = {headers: req.headers, files: req.files, body: req.body};
		res.end();
	});

	await storage.ready();
	await request(app)
		.post('/url')
		.attach('photos', files[0])
		.attach('photos', files[1]);
}
github BigDataBoutique / ElastiQuill / backend / src / services / storage.js View on Github external
.then(storage => {
      if (storage) {
        uploadHandler = multer({ storage }).any();
      }
    })
    .catch(err => console.log(`Failed to configure storage: ${err.message}`));
github tinacms / tinacms / packages / @tinacms / api-git / src / upload.ts View on Github external
export function createUploader(tmpImgDir: string) {
  const tmpImgStorage = multer.diskStorage({
    destination: function(req: any, file: any, cb: any) {
      verifyUploadPath(tmpImgDir, () => {
        cb(null, tmpImgDir)
      })
    },
    filename: function(req: any, file: any, cb: any) {
      cb(null, file.originalname)
    },
  })
  return multer({ storage: tmpImgStorage })
}
github letterpad / letterpad / api / app_____.js View on Github external
}
        };
    })
);

var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, path.join(__dirname, "../public/uploads/"));
    },
    filename: function(req, file, cb) {
        let ext = path.extname(file.originalname);
        cb(null, file.fieldname + "-" + Date.now() + ext);
    }
});

var upload = multer({ storage: storage }).single("file");

app.post("/upload", (req, res) => {
    upload(req, null, function(err) {
        res.json("/uploads/" + req.file.filename);
    });
});

module.exports = app;
github opencollective / backyourstack / src / server / index.js View on Github external
nextApp.prepare().then(() => {
  const server = express();
  const upload = multer();

  server.use(
    favicon(path.join(path.dirname(__dirname), 'static', 'favicon.ico')),
  );

  server.use(cookieParser());

  server.use(
    expressSession({
      name: 'sessionId',
      secret: sessionSecret,
      resave: false,
      saveUninitialized: false,
      cookie: cookieOptions,
    }),
  );

multer

Middleware for handling `multipart/form-data`.

MIT
Latest version published 2 years ago

Package Health Score

79 / 100
Full package analysis