Upload file and save to server locally

could someone show me how upload a file from a form and pass it to server method using meteor call. I want to understand how to do it without needing any atmosphere packages.

thank you

I strongly recommend using a package, either atmosphere or npm for handling uploads. But…

The easiest to implement method to send via DDP is to convert the file into an ArrayBuffer blob and send that as a method argument.
This will be a little slow as the binary needs to be serialized into a EJSON string and sent over the websocket. You’re also likely to run into size limits

A more standard way of handling uploads is to create an /upload HTTP endpoint using WebApp.connectHandlers. Then you can make a standard multi-part HTTP post request and handle that as you would with any Node app.

3 Likes

I am having trouble getting the file from FormData

could you show me what it should look like

thank you please :slight_smile:

Heres a simplified way…

Client side POSTS the file to /api/upload straight in the body without FormData/multipart:

const input = document.getElementById('fileinput');
const res = await fetch(`${baseUrl}/api/upload`, {
	method: 'POST',
	body: input.files[0],
});

Server side just slurps it up with no parsing multipart.

const app = express();

const uploadFile = Meteor.bindEnvironment(async (req, res, next) => {
	const output = fs.createWriteStream('/tmp/upload123');
	req.pipe(output, {end: true});
	output.on('close', () => res.end());
});

app.post('/upload', uploadFile);
WebApp.connectHandlers.use('/api', app);
3 Likes

Why don’t use this one? GitHub - veliovgroup/Meteor-Files: 🚀 Upload files via DDP or HTTP to ☄️ Meteor server FS, AWS, GridFS, DropBox or Google Drive. Fast, secure and robust.

2 Likes

Cool! It’s been a while since I rolled my own uploads, so didn’t realise it was this easy now :star_struck:
Like, this is even easier than most packages :sweat_smile:

Curiously, MDN still recommends the FormData approach

1 Like