我是 Node JS 新手,我已经成功创建了一个允许文件上传的页面,并在浏览器中显示图像。我遇到的唯一问题是它显示到一个页面,并将文件名附加到 URL 末尾,如下所示: localhost:8888/tmp/car.png我希望能够在浏览器中看到它,网址如下:本地主机:8888/汽车
任何建议,我们将不胜感激,谢谢!!!!
var express = require("express");
var app = express()
/// Include the express body parser
app.configure(function () {
app.use(express.bodyParser());
});
var form = "<!DOCTYPE HTML><html><body>" +
"<form method='post' action='/upload' enctype='multipart/form-data'>" +
"<input type='file' name='image'/>" +
"<input type='submit' /></form>" +
"</body></html>";
app.get('/', function (req, res){
res.writeHead(200, {'Content-Type': 'text/html' });
res.end(form);
});
/// Include the node file module
var fs = require('fs');
/// Post files
app.post('/upload', function(req, res) {
fs.readFile(req.files.image.path, function (err, data) {
var imageName = req.files.image.name
/// If there's an error
if(!imageName){
console.log("There was an error")
res.redirect("/");
res.end();
} else {
var newPath = __dirname + "/uploads/fullsize/" + imageName;
/// write file to uploads/fullsize folder
fs.writeFile(newPath, data, function (err) {
/// let's see it
res.redirect("/uploads/fullsize/" + imageName);
});
}
});
});
app.listen(8888)
只需使用:
express.static('uploadPath')
对于:localhost:8888/car.png
我是一名优秀的程序员,十分优秀!