I am building a node.js application that uses pdf.js to read pdf files, but much like other js, pdf.js does not allow cross origin requests. So, I need a way to save files selected with a file input to my pdf directory. I'm not so great with node so make it as simple as possible if you can.
-
please post your code so we can help.Shaan– Shaan2015-02-23 18:12:37 +00:00Commented Feb 23, 2015 at 18:12
-
I don't have any code regarding the upload yet. Would you mind posting the the code for this POST route? Or refer me to a helpful documentation of an npm library.Isaac Wasserman– Isaac Wasserman2015-02-23 18:52:13 +00:00Commented Feb 23, 2015 at 18:52
Add a comment
|
1 Answer
Here is a basic idea of what you need:
1st, require and use module 'connect-multiparty'. This will expose the req.files object in node.
var multipart = require('connect-multiparty');
app.use(multiparty({});
Then, in your controller method, require the 'fs' module, and use it to save the uploaded file.
var fs = require('fs');
fs.writeFileSync("myFileName", req.files.file.ws.path, function(err) {
if(err) { console.log(err); }
else { console.log("file uploaded"); }
});
Being familiar with node will help, but the two basic libraries you need to perform this are the aforementioned https://www.npmjs.com/package/connect-multiparty and http://nodejs.org/api/fs.html
edit: see the link in the comments below. this answer is incomplete and is better explained in the link
3 Comments
Isaac Wasserman
Also, what does file.ws.path mean? What do I have to replace those with?
Grant Fowler
The file.ws.path should be where the uploaded file is stored in the /tmp folder, I believe. The first part (app.use) should be in your application, and the second should be in your post method. A few things that I forgot: in your html form, make sure you have "enctype="multipart/form-data", and make sure to name the input field "file".
Grant Fowler
so, my answer above isn't completely correct. see this link (which uses an old version of express, but using multiparty should fix that) howtonode.org/really-simple-file-uploads . You need to first read the file, then write it.