gpt4 book ai didi

node.js - 如何让文件上传图像显示在某些URL Node JS上

转载 作者:太空宇宙 更新时间:2023-11-04 02:37:03 25 4
gpt4 key购买 nike

我是 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

关于node.js - 如何让文件上传图像显示在某些URL Node JS上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21372851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com