使用Node.js的Express框架进行文件上传

时间:2024-11-05 19:33:44

我们先创建一个Express项目,要使用文件上传的功能还需要下载multer模块。

npm install --save multer

下面我们在public文件夹下创建upload.html,内容如下:

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<h3>文件上传:</h3>
选择一个文件上传: <br />
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="content" />
<br />
<input type="submit" value="上传文件" />
</form>
</body>
</html>

然后再routes文件夹下创建upload.js,内容如下:

 var fs = require('fs');
var express = require('express');
var multer = require('multer'); var router = express.Router();
var upload = multer({dest: 'upload_tmp/'}); router.post('/', upload.any(), function(req, res, next) {
console.log(req.files[0]); // 上传的文件信息 var des_file = "./upload/" + req.files[0].originalname;
fs.readFile( req.files[0].path, function (err, data) {
fs.writeFile(des_file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files[0].originalname
};
console.log( response );
res.end( JSON.stringify( response ) );
}
});
});
}); module.exports = router;

最后在app.js里添加下面的代码:

var upload = require('./routes/upload');
app.use('/upload', upload);

执行,访问下面的地址即可:

http://localhost:3000/upload.html

相关文章