Upload file using NodeJS and node-formidable - javascript

I succeed uploading file using node.js and the formidable module yet,
the file that got save on the disk is in some kind of a bad format ( bad encoding)
e.g. if I upload an image I can't view it, if I upload a txt file gedit provide the following msg:
"gedit has not been able to detect the character encoding.
Please check that you are not trying to open a binary file.
Select a character encoding from the menu and try again."
here is the code:
form.encoding = 'utf-8';
form.parse(req, function(err, fields, files) {
fs.writeFile('test.js', files.upload,'utf8', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});

The problem is the that files.upload is not the content of the file, it is an instance of the File class from node-formidable.
Look at:
https://github.com/felixge/node-formidable/blob/master/lib/file.js
Instead of trying to write the file to disk again, you can just access the path to uploaded file like this and use fs.rename() to move it where you want:
fs.rename(files.upload.path, 'yournewfilename', function (err) { throw err; });

Is the form set to enctype="multipart/form-data"?
I've only used formidable with Express - the Express example works fine:
https://github.com/visionmedia/express/tree/master/examples/multipart

Related

How to edit File in perfoce with node js?

If i have the code below how can i edit the specific file and make the right corrections?
var p4 = require('C:/Program Files/nodejs/node_modules/p4');
var File = process.argv[2];
p4.edit(File, function(err, data) {
if (err) {
console.error(err.message);
}
console.log(data);
});
Your code looks correct to open the file for edit. If that returns any errors when you run it, you should post those here, but I'll assume that it returns a success message ("(file) opened for edit").
Opening the file for edit means that it is made writable on the local filesystem (i.e. the one where this code is running -- the file is the one you passed as an argument to the edit command). To actually modify the file you can use any other function at your disposal.

How to download a URL in JavaScript (Nodejs)?

I used this link to make an original link into a download link:
https://milanaryal.com/2015/direct-linking-to-your-files-on-dropbox-google-drive-and-onedrive/
Now how do I actually use that download link to download the file in JavaScript? I want to do something like:
link = 'https://drive.google.com/uc?export=download&id=FILE_ID';
let x = download(link); //now x is the download file
I looked it up and it seems like there are ways of doing this with HTML/jQuery, but I am not using those because I am working on the server side with Nodejs. I am doing this download thing because I want to check if the file is a pdf or text, parse the text, and then search through it using Elasticsearch.
It's easiest to use a module such as Request to do a HTTP get from a node script.
For example:
var request = require('request');
request.get('https://drive.google.com/uc?export=download&id=FILE_ID',
function(err, res, body){
if(err) return console.log(err);
console.log(body);
});
Once the file has downloaded, the callback function is run with the downloaded file in the body variable
If you only want to download the file, open it, search for data and delete it, you can easily edit this code snippet: https://stackoverflow.com/a/11944984/642977

upload a file in Node.JS

I'm using multiparty for uploading a file; I'm so new to Node.JS and streaming; so my question is, is it right if I stream the file by the file.path which is returned in form.parse() like the way I'm doing in my attempted code? I mean this is absolute path and obviously is working on localhost because it is the absolute path of my current server which is localhost, but is it going to work when the user attempts to upload a file from their computer too?
form.parse(req, function (err, fields, files) {
var rs= fs.createReadStream(files.file[0].path);
var fileDate;
rs.on('readable', function () {
while (null !== (chunk = rs.read())) {
fileDate += chunk;
}
});
rs.on('end', function () {
console.log('importedData', fileDate);
});
});
Thanks, please let me know if you need more clarification!
That looks correct. By default, uploaded files are put in a temporary folder, if you're using Linux this will likely be /tmp, your users' files will end up in the same place when they upload their files through your front-end.

error ENOENT,open with gridFS and node js

I am trying to save a project and its file using GridFS. I want to save project first and use "_id" of project as metadata for file.
Here is my code:
newProject.save(function (err,project) {
if (err) {
console.log('save error', err);
}
console.log("project added");
var id=poject._id;
var filepath = req.files.file.path;
var filename = req.files.file.name;
var writestream = gfs.createWriteStream({ filename: filename, metadata:id });
console.log(filepath);
fs.createReadStream(filepath)
.on('end', function() {
})
.on('error', function(err) {
console.log("error encountered"+err);//ENOENT,open error
})
.pipe(writestream);
});
I am getting following error:-
ENOENT, open '/tmp/45e85388793de'
I know that this error comes when the directory does not exists. As you can see I am writing the file after saving the project since I need to link the file to the project. That's why I have written the code to save the file inside callback function of project.save() but it is not working there. If I put the same code outside the .save block the same code works perfectly for same path. (I have displayed the path both inside and outside and they are same)
Finally I was able to fix this myself:-
File is saved in a temporary location. When you are inside the callback function your file is removed from that location and you are getting "No such file" error. Path and other variables still exists as part of js and that's why you are able to print them in console.
Solution: Above(Outside) callback function move your file to some other permanent location using:
fs.rename(req.files.file.path, "./someKnownPath/filename");
Keep note of that location. In your callback function use the new location as path and try saving the file in gridfs. Once the file is saved you may delete it file from that location(/someKnownPath/filename).

OSX Node.js File upload ENOENT

I've been working with Node.js for a project and everything has been going well until now. I'm using express as well with node. Overall my goal is extremely simple...upload an image to the server in an uploads folder. The odd thing is the upload itself actually works but when I go to use the "rename" function it says the path is wrong/permissions with this error: ENOENT.
I've also tested to make sure that the path is 100% correct when being used by calling the read function to check for the file path. Seems to only break when it tries to modify the file so I've deduced it's a permissions issue (unless there's some sort of special requirement for the rename function). I noticed that every time a file gets uploaded the permissions set to "custom" and only give read permissions to every user except my username. I'll post the code that's related to this problem below:
/app/routes.js
var fs = require('fs');
app.post('/api/file-upload/:page_id', function(req, res) {
// fs.readFile(tmp_path, function (err, data) {
// if (err) throw err;
// console.log(data);
// });
var target_path = './public/images/' + req.files.featuredimg.name;
fs.rename(req.files.featuredimg.path, target_path, function(err) {
if (err) throw err;
fs.unlink(tmp_path, function() {
if (err) throw err;
res.send('File uploaded to: ' + target_path + ' - ' + req.files.featuredimg.size + ' bytes');
});
});
});
server.js
app.use(express.bodyParser({uploadDir:'./uploads'}));
Everything ends up in the root folder next to server.js in /uploads which works as intended. I just can't seem to modify them. I've tried everything I can think of and have looked up the problem. Hopefully it's a simple fix.
Hopefully someone out there can help me out with this problem. I'd really appreciate it!
Make sure you have created images folder under public. I had similar issue.

Categories