Node.js Uploading an Image from Single Page App
-
21-12-2019 - |
Question
I'm using express.js 3.5.1
as the backend for my app. It's just a basic forum, but I want my users to be able to upload images. I can't use a simple form to upload since it will cause a redirect. The only solution I've found that seems like it may be possible is with socketio-file-upload. I'm hesitant about including socket.io
just for the sake of uploading images though. Is there any way to do this with a simple XMLHttpRequest
or Ajax
request? Or maybe another method I'm not thinking of?
Here's the server code I currently have to handle the incoming request from a form:
app.post('/save-image', checkSession, function(req, res)
{
actionLog( req.session.username, 'is trying to upload a file' );
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files)
{
console.log(files);
res.send({ error: 'not setup yet'
})
});
});
Solution 2
The problem I was having had to do with my request router and not the requests themselves. Turns out it didn't support Multipart/Form-Data type requests.
Switched to http-proxy and everything resolved itself.
The node module Bouncy DOES NOT support Multipart/Form-Data requests.
OTHER TIPS
You can don't change your code. Simply send to the client urls of images when you loads all posts.
The scenario will be like this:
1) You upload image with simple POST request.
2) After this running AJAX call to get all posts for instance "/posts".
3) The controller returns all posts for example : [{ id: 1, text: "asd", image: "yourhost.com/images/image.png"}, ...]
4) Using your jquery or other things you reload view.