Is there a way to accept multipart forms on meteorjs? i.e. image uploads? - node.js

I want to be able to add image uploads to a site I'm working on, but I don't know how that is supposed to work with meteorjs. Is there a way to accept multipart forms on meteorjs? i.e. image uploads?
I could always rackup a small sinatra app for file uploads but I'd rather not.

You need to write a middleware to accept such requests.
WebApp.connectHandlers.stack.splice(0, 0, {
route: '/your/url/for/inputs',
handle: function(req, res, next) {
// Handle request and response
// just like you would do in node.js.
// Make sure to wrap your db calls in Fibers.
// Use next() if you change your mind
// and don't want to handle this request after all.
},
});

Looks like eventminded has a file upload package you could use.
https://www.eventedmind.com/posts/meteor-build-a-file-upload-package

Related

How can I build a web app that I can send files to for further manipulation?

I want to build a NodeJS server that accepts a .wav file (1Mb) sent to its single endpoint, then changes the file through AudioContext API and then sends back the response with the result?
The server shouldn't store anything, so, no database required.
How can I achieve this? (or, please correct me if don't understand how things work)
I would do this with express: https://expressjs.com/
and as middleware add express-fileuplaod: https://www.npmjs.com/package/express-fileupload
app.post('/upload', function(req, res) {
console.log(req.files.foo); // the uploaded file object
});
instead of the console.log(); you'd make a readable stream / buffer and then use it in the
AudioContext API
here is also a interesting Article explaining to use this:
https://www.russellgood.com/process-uploaded-file-web-audio-api/

Why use multer rather than manually upload your files from controller

So im new on using expressjs, usually i choose Laravel as my backend. but because some certain consideration, i choose expressjs.
On Laravel, when we handling file upload, we can write upload logic everywhere, its your freedom to do that. You can encapsulate it inside your model function, or put it on service, or anywhere you want.
But when i use expressjs, so many articles on internet that recommend us to use multer for upload your file. As my background is using Laravel previously, i found its weird to use multer. Its because multer is a middleware. Why on earth we use middleware to upload our images/files.
With this i cant encapsulate my business logic into one service and its make the code separated and with this thats mean i need to maintain one business logic from multiple place.
Could you explain me why everyone choose multer ?
why dont just upload it to our local storage manually ?( actually for now i dont know how to do this ).
What is pros on mins from using this library ?
multer is a body parsing middleware that handles content type multipart/form-data
That means it parses the raw http request data which are primarily used for file upload, and makes it more accessible (storing on disk / in memory /...) for further processing.
Without multer, you would have to parse the raw data yourself if you want to access the file.
With this i cant encapsulate my business logic into one service and
its make the code separated and with this thats mean i need to
maintain one business logic from multiple place. Could you explain me
why everyone choose multer ?
multer, just like other middlewares, can be used at the root for all routes, but can also be put on only specific routes too.
More on express middleware
First of all, Express/body-parser does not handle file uploads natively, so that is why you see other libraries being loaded to handle them. They are all going to be loaded as middleware so they can be injected into the request and handle that a file was actually uploaded.
Coming from a Symfony background, I understand where you are coming from with wanting to handle things more manually, as I do the same. There are other alternatives to multer; for example I use express-fileupload which allows you to load the the uploading middleware for your entire app, and then you can use req.files to handle your uploads. For example:
// load the file upload library as app middleware
const fileUpload = require('express-fileupload');
app.use(fileUpload({
limits: { fileSize: 50 * 1024 * 1024 },
}));
Then let's say you have a file input named 'foo':
<input name="foo" type="file" />
In your route you would handle it like so:
// now handle a file upload
app.post('/upload', function(req, res) {
console.log(req.files.foo); // the uploaded file object
});
The file-upload documentation has examples for the req.files object as well as options you can pass to the middleware itself.

POST Request creates file, followed by GET Request to download

Trying to do something seemingly basic.
I'd like to create a POST request through which I'll be sending JSONs. These JSONs will be created into files, which I'd like to return to the user via download.
The use case for this is that I'm building an application which takes a form and converts it into a JSON for upload to a MongoDB database. Users can load these JSONs into the application to re-load their old records as templates.
This is how I'm approaching it as of now:
// Download JSON Previews
var jsondownload = {};
// Grabs the JSON from POST request
app.post('/api/download', function(req, res, next){
jsondownload = {};
var json = req.body;
jsondownload = json;
res.json(jsondownload);
next();
});
// Immediately downloads the JSON thereafter
app.get('/api/download', function(req, res){
res.set({"Content-Disposition":"attachment; filename='test.json'"});
res.send(jsondownload);
});
What's the right way to do this?
There is no one "right" way to do it, but a few solutions include:
Remove the GET route handler (and the jsondownload variable) completely and just respond immediately with the Content-Disposition set appropriately. This is the better of the 3 because it reduces code and keeps things simple.
Use a simple redirect in your POST route handler. Instead of responding with the JSON immediately, you would do res.redirect('/api/download').
Do more or less what currently doing, but move the logic (the res.set() and res.send()) to a separate function that gets called from both route handlers.

Where does the /api directory come from in an Express application?

For example:
router.get('/api/todos', function (req, res){
db.todos.find(function (err, data){
res.json(data);
});
});
I am having a hard time understanding what '/api/todos/ actually means. I don't have a directory name either one of these in my application. What exactly is this and where is it?
/api/todos/ does not refer to a local file, it corresponds to a URL request. In the function you provided, if you were to add this route to an express app then visit http://localhost/api/todos, the server would respond with the JSON data returned from the database query you are making.
router.get('/api/todos', function (req, res){
This first line accepts all GET requests to /api/todos, and passes the req and res objects into a callback for you to work with. See http://www.murvinlai.com/req-and-res-in-nodejs.html for an explanation of those objects.
db.todos.find(function (err, data){
Here, it is assumed that you have a db object which may perform database lookups based on some kind of input parameters.
res.json(data);
The res.json method simply sends the JSON back to the client that requested it.
See https://www.packtpub.com/books/content/understanding-express-routes for further info on routing in express.
That's not a directory. That's a URL. Routers route URLs to resources. It could be files, it could be other URLs or most commonly it could be some javascript logic that generates the response you want (JSON, XML, HTML, PDF etc.)

node express upload file with mean stack

I should implement an upload form
I thought of using bodyparser but I read
http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html
so what's the way to upload a file with express using the mean stack ?
may be formidable or other modules ?
That warning is specifically against adding the express.bodyparser middleware to your entire stack as it adds express.multipart to all POST endpoints and therefore file uploads are automatically accepted at all POST endpoints. By default the framework automatically saves any uploaded files to /tmp and so unless you are cleaning them up an attacker could flood your disk with uploaded files.
If you want to avoid using additional modules, what you should do is implement express.multipart on the endpoint(s) where you want to allow file uploads. Here's what I'm talking about:
var express = require("express")
, app = express();
// middleware (no bodyparser here)
app.use(express.json());
app.use(express.urlencoded());
// average GET endpoint
app.get("/", function(req,res) {
res.send('ok');
});
// average POST endpont
app.post("/login", function(req,res) {
res.send('ok');
});
// File upload POST endpoint
app.post('/upload', express.multipart, function(req, res) {
//File upload logic here
//Make sure to delete or move the file accordingly here, otherwise files will pile up in `/tmp`
});
Note the inclusion of express.multipart in the file upload endpoint. This endpoint will now process multipart file uploads, and assuming you handle them correctly they won't be a threat.
Now, having told you all of this, Connect is moving to deprecate multipart due to this exact issue, but there don't seem to be any plans to add a stream based file upload replacement. What they instead recommend is that you use node-multiparty which uses streams to avoid ever placing a file on disk. However, there don't seem to be any good references I can find for using multiparty as a middleware without saving files though, so you'll have to contact the author of multiparty or take a closer look at the API for implementing it with Express.
I created an example that uses Express & Multer - very simple, avoids all Connect warnings
https://github.com/jonjenkins/express-upload

Resources