如何使用node.js和express来上传,显示和保存图像 [英] How to upload, display and save images using node.js and express
问题描述
我需要上传图像并显示它,并保存它,以便在刷新本地主机时不会丢失它。这需要使用上传按钮完成,该按钮提示进行文件选择。
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.
我正在使用node.js并表达服务器端代码,对Web应用程序编程来说真的很新,任何帮助都将不胜感激。
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.
感谢提前。
推荐答案
首先,您应该使用 HTML
文件输入元素。以下是一个简单的例子:
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>
那么你应该加载 express.bodyParser()
中间件:
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!");
});
}
// ...
});
显示上传的文件,我假设你已经有一个 HTML
其中包含图像标签的页面:
to show the uploaded file, I assume you already have a HTML
page with an image tag in it:
<img src="/image.png" />
现在您可以使用 res.sendFile
提供上传的图像:
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'));
});
这篇关于如何使用node.js和express来上传,显示和保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!