并非如此,它保存在您的计算机中,在您选择的目录中。
这是用于 multer 上传的纯 html 表单。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form accept="image/x-png,image/gif,image/jpeg" enctype="multipart/form-data" action="/profile" method="post">
<input type="file" name="avatar" value="">
<input type="submit" name="" value="ssss">
</form>
</body>
</html>
这是我们的后端代码。在存储中,我选择将文件上传到/upload 目录下的位置,并为它们提供当前时间的文件名。我们声明了upload 变量进行设置,然后我们使用upload.single('avatar'),当我们收到一个发布请求时,我们在回调之前声明它。 avatar 这里是 input 标签内的 html 表单中的文件名。在回调中,我们可以使用req.file 访问我们的文件。模块以这种方式保存文件,非常好用。
var express = require('express')
var multer = require('multer')
var app = express()
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + '/uploads') //you tell where to upload the files,
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + '.png')
}
})
var upload = multer({storage: storage,
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...')
},
});
app.set('view engine', 'ejs');
app.get('/', function(req, res, next){
res.render('mult'); //our html document
})
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
console.log(req.file);
return false;
})
请确保您提供 png 或 jpeg 或任何您想使用的图像和扩展名,否则它将不会被视为计算机中的图像。
更新您的问题
如果您想在不刷新页面的情况下向客户端显示图像,只需在客户端浏览器上使用带有 get 请求的 AJAX。您可以将文件上传到您的网络服务器 或网络服务器 并从那里检索图像。比如我在stackoverflow中的头像保存为 here
您可以在 get 请求中使用参数来接收来自服务器的所有文件。
例如,假设客户端向/uploads/imageOfApet.png 发出获取请求。
app.get('/uploads/:theImageName', function(req, res){
console.log(req.params.theImageName); //returns the imageOfApet.png
var theName = req.params.theImageName; //imageOfApet.png
res.sendFile(__dirname + "/uploads/" + theName); //Sending the user the file
})