I need to upload an image, and display it, as well as save it so that I don't lose it when I refresh the localhost. This needs to be done using an "Upload" button, which prompts for a file-selection.
I am using node.js and express for the server-side code, and am really new to web application programming, Any help would be appreciated.
Thanks is advance.
First of all, you should make a HTML form with a file input element in it. Here's a simple example:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
then you should load express.bodyParser() middleware:
app.use(express.bodyParser({uploadDir:'/path/to/temporary/directory/to/store/uploaded/files'}));
and define a route to handle the form post:
var path = require('path'),
fs = require('fs');
// ...
app.post('/upload', function (req, res) {
var tempPath = req.files.file.path,
targetPath = path.resolve('./uploads/image.png');
if (path.extname(req.files.file.name).toLowerCase() === '.png') {
fs.rename(tempPath, targetPath, function(err) {
if (err) throw err;
console.log("Upload completed!");
});
} else {
fs.unlink(tempPath, function () {
if (err) throw err;
console.error("Only .png files are allowed!");
});
}
// ...
});
to show the uploaded file, I assume you already have a HTML page with an image tag in it:
<img src="/image.png" />
Now you can use res.sendFile to serve the uploaded image:
app.get('/image.png', function (req, res) {
res.sendfile(path.resolve('./uploads/image.png'));
});