On a web-application that I am working on, users can upload a PDF file. I would like to read this PDF file to a buffer of bytes, which I can pass on to my database to save it as a BLOB. I am doing this in Node, using the Express framework.
Currently, I have the following:
Upload form:
<form id='uploadForm' method='post' enctype='multipart/form-data'>
<div class='form-group'>
<div class='form-inline'>
<label for='file'>File:</label>
<input type='file' name='file'>
</div>
</div>
<!--- some other fields --->
</form>
Server side:
router.post('/', function(req, res) {
var file = req.files.file;
var path = file.path;
var fsiz = file.size;
var buffer = new Buffer(fsiz);
fs.read(file, buffer, 0, fsiz, 0, function (err, bytesRead, buffer) {
console.log(err);
console.log(bytesRead);
console.log(buffer);
});
});
This gives me a Bad argument error on the fs.read function call. What is wrong and how can I fix it?
fs.read()'s first argument is supposed to be a file descriptor object, as returned by fs.open().
You can either first call fs.open(), or else use fs.readFile(), which takes a path:
router.post('/', function(req, res) {
var file = req.files.file;
var path = file.path;
var fsiz = file.size;
var buffer = new Buffer(fsiz);
fs.open(path, 'r', function(err, fd) {
fs.read(fd, buffer, 0, fsiz, 0, function (err, bytesRead, buffer) {
console.log(err);
console.log(bytesRead);
console.log(buffer);
});
});
});
router.post('/', function(req, res) {
var file = req.files.file;
var path = file.path;
var fsiz = file.size;
var buffer = new Buffer(fsiz);
fs.readFile(path, function (err, data) {
console.log(err);
console.log(data);
});
});