im trying to create a download for a user but somehow my download doesnt work even tho it works?Let me explain :
Server post request :
app.post('/downloadRequest', function (req, res) {
var fileName = "testname.txt";
var file = __dirname +'/test.txt';
res.download(file,fileName,function(err) {
if(err) throw err;
console.log("downloaded");
});
});
When im calling it,no error message appears. Also it shows "downloaded" in the console.Im clueless..
Related
I've created a SNS web application (using node.js) where people can upload pictures (using cloudinary) into collections.
The application works perfectly on a cloud-based IDE I use for writing code; however, after pushing it to heroku, the image upload no longer works. I don't get any error message in my console, even though I think it should be console.logging it, however the error flash happens and the image doesn't upload.
Here is my code:
router.post("/", middleware.isLoggedIn, upload.single('image'), function(req, res){
cloudinary.v2.uploader.upload(req.file.path, function(err, result) {
if (err) {
//if error
console.log(err.message);
req.flash("error", "Can't upload image, try again later.");
return res.redirect("back");
}
//else
// add cloudinary url for the image to the campground object under image property
req.body.image = result.secure_url;
req.body.imageId = result.public_id;
// add author to campground
req.body.author = {
id: req.user._id,
username: req.user.username
};
I've tried searching other posts for a possible reason; but I can't find anything that matches my situation. If anyone can help...please, your advice would be greatly appreciated!
Thank you.
Sorry! The problem was the CLOUD_NAME config variable had '' marks around it.
If anyone is having similar issues, try removing the quotes around the name variable.
Scenario:
I have to send user file which is stored remotely in a server(cloudinary) to browser. I'm able to request an image from server and then pipe it to browser but it's not working for other files like pdf, excel sheet, etc.
exports.fetchFile = function(req, res, next){
var fileUrl = "/" + req.params.fileUrl;
console.log(fileUrl);
async.auto({
'A': function(callback) {
var queryObj = { 'myUrl' : fileUrl};
// DB Query to retrieve user file information like url, type, etc.
UserFileCtrl.fetchUserFile(queryObj, callback);
}
}, function(err, results){
if(err) {
return res.send(500, "error");
}
var secureUrl = results['A']['secureUrl'];
var fileType = results['A']['fileType'];
// this will be "application/pdf" for pdf
res.setHeader('Content-Type', fileType);
request(secureUrl).pipe(res);
});
}
Above code gives an empty pdf file to client whereas if I open directly the cloudinary url then it's coming properly. I'm breaking my head for a long time but not able to get something out of it.
I really appreciate your help.
Edit: I found this similar question also: Express server send empty PDF file but this is also not working for me. I tried disabling connnect-livereload but even then it's not working.
The issue is happening only for pdfs. All other formats are working fine.
So, bit of an odd problem. I have a bunch of media files saved as base64 strings in mongo, some are images, some are videos.
I made an API for getting the media files:
app.get('/api/media/:media_id', function (req, res) {
media.findById(req.params.media_id)
.exec(function (err, media) {
if (err) {
res.send(err);
}
var file = new Buffer(media.file, 'base64');
res.writeHead(200, {'Content-Type': media.type, 'Content-Transfer-Encoding': 'BASE64', 'Content-Length': file.length});
res.end(file);
});
});
Now, images have no problems. They load just fine, both directly from the API, and when I call the API from a front-end (for example <img src="/api/media/23498423">)
THE PROBLEM
If I fetch a video from a front-end, like the images - but with a video- or object-tag:
<video src="/api/media/3424525" controls></video>
there's no problem, but if I load the video in a browser directly from the API:
http://localhost:8080/api/media/3424525
the server process crashes, no errors. It simply just freezes up. And we're not talking about huge video files - it's a 1.5MB video.
The media type in the header for all the videos I'm testing with is video/mp4. Oh, and just to be clear: if I do the same with images, everything works perfectly.
EDIT:
Okay, so as suggested by #idbehold and #zeeshan I took a look at gridfs and gridfs-stream, and for the purpose of my app, this certainly is what I should have used in the first place. However, after implementing gridfs in my app, the problem still persists.
app.get('/api/media/:media_id', function (req, res) {
gfs.findOne({ _id: req.params.media_id }, function (err, file) {
if (err) {
return res.status(400).send(err);
}
if (!file) {
return res.status(404).send('');
}
res.set('Content-Type', file.contentType);
res.set('Content-Disposition', 'inline; filename="' + file.filename + '"');
var readstream = gfs.createReadStream({
_id: file._id
});
readstream.on("error", function (err) {
console.log("Got an error while processing stream: ", err.message);
res.end();
});
readstream.pipe(res);
});
});
When I call the media file (be it image or video) from a front-end, within a HTML tag, everything works out fine. But if I load a video (again, smallish videos from 1.5mb to max 6mb total size) directly in the browser, the server process freezes. To be a bit more clear: I am testing on windows, and the server app (server.js) is run in console. The console and the process it is running is what freezes. I cannot load any more pages/views in the node app, and I cannot even stop/kill/shutdown the node app or the console.
Streaming videos directly to/from GridFS using gridfs-stream either with mongodb-native db instance or mongoose.
var mongo = require('mongodb'),
Grid = require('gridfs-stream'),
db = new mongo.Db('yourDatabaseName', new mongo.Server("127.0.0.1", 27017)),
gfs = Grid(db, mongo);
//store
app.post('/video', function (req, res) {
req.pipe(gfs.createWriteStream({
filename: 'file_name_here'
}));
res.send("Success!");
});
//get
app.get('/video/:vid', function (req, res) {
gfs.createReadStream({
_id: req.params.vid // or provide filename: 'file_name_here'
}).pipe(res);
});
for complete files and running project:
Clone node-cheat direct_upload_gridfs, run node app followed by npm install express mongodb gridfs-stream.
Truly an odd problem...
I could be way off, but it's worth a shot:
One of the differences when opening a url directly from the browser is that the browser will also try to fetch http://localhost:8080/favicon.ico (while trying to find the tab icon). Maybe the problem is not related to your video code, but rather to some other route, trying to handle the /favicon.ico request?
Have you tried using wget or curl?
I don't know the answer, maybe this is a dumb suggestion, but what is the browser you are using? Maybe something from Microsoft causes the problem...
I would like to upload multiple image files to my server. On the client side I m using dropzone.js. My back-end server is sails.js and I would like to use formidable in order to update the client with a progress-bar ( I am fairly new to sails.js and node.js)
This is my controller (written with typescript)
export var upload = function (req: express.Request, res: express.Response, next) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
});
form.on('progress', function (bytesReceived, bytesExpected) {
// calculating perscent and logging progress message
});
form.on('error', function (err) {
console.error(err); // --> here I get "Request aborted"
});
form.on('end', function (fields, files) {
// here I save files to disk with fs-extra and I
// send back to client appropriate status
});
}
I keep getting 'Request aborted' in the error handler. I have made a few search on stackoverflow and on google without findind a clear answer. The problem seems to be related to multi-part form data and the appropriate express middleware to use in order to parse the body. How can I set my sails.js application in order to upload a file using dropzone.js on the client and sails+formidable on the server?
Any help will be greatly appreciate
With Dropzone and Sails.js, you have to:
add the definination of the filename in dropzone configuration:
Dropzone.options.myDropzone = { paramName: "fileName" }
use this command to get back the uploaded file:
req.file('fileName').upload(function (err, uploadedFiles) {
});
uploadedFiles contains the file
I am trying to post a comment to a nodejs server but i am getting 404 error. I have used cors module on server side to handles cors request. I am using typescript.
cors module: https://github.com/troygoode/node-cors
var app = express();
app.use(cors());
(<any>app).options('*', cors()); // include before other routes
app.use((<any>app).router);
Following is my endpoint code
app.post("/api/object/addcomment/:id", authenticatebearer(), (req, res) => {
var id = this.ParseInt(req.params.id);
var comment: string = req.body.CommentText;
if (this.IsNullOrUndefined(id) && this.IsNullOrUndefined(comment))
return this.SendInputError("input is empty.", res);
(new OM.ObjectManager()).AddComment(req.user.userId, id, comment, (err, commentId) => {
if (err) return this.SendInternalError(err.message, res);
return res.json(commentId);
});
});
I am calling above endpoint from angularjs app,
myApp.config(function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
function addComment(id, comment, callback) {
var URL = Client.Config.RestUrl + "api/object/addcomment/" + id.toString() + '?access_token=' + this.RootScope.LogInUser.accessToken;
this.$http.post(URL, JSON.stringify({ CommentText: comment }))
.success((commentId, status) => {
callback(null, commentId);
})
.error((data, status) => {
callback(new Error("An unexpected error occured while adding comment."), null);
});
}
This code is working properly in the desktop environment. Please see the network log from chrome,
In phonegap, the function call executes successfully and the comment is added to the system but the $http.post is giving 404 error (gets response in error callback). Please see the network log from adb debugging tool (this works with android 4.4.2),
I am struggling for this from last two day. Unable to find a solution. Please help me.
Thanks in advance. Sorry for my english.