express是个非常好的基于noe的web框架…
我们直接上实列代码吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
</style>
</head>
<body>
<input type="file" onchange="UP()"/>
<script>
function upfile(e){
console.log(e.files);
}
function UP(){
console.log(event.target.files[0])
let img = event.target.files[0];
let Form = new FormData();//formdata上传
Form.append('avatar', img);
$.ajax({
url: '上传express路由url',
type: 'post',
anync: true,
processData: false,
contentType: false,
data:Form,
success: function (data) {
console.log(data)
}
});
}
</script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
</html>
var express = require('express');
var app = express();
const fs = require('fs')//node的文件读取模块
const path = require('path')
const bodyParser = require('body-parser')// 引入body-parser中间件,用来处理post请求体body中的数据
const multer = require('multer')// 引入multer中间件,用于处理上传的文件数据
app.use(express.static('public'))// 静态资源
app.use('/static', express.static('public'))// 静态资源地址
app.use(multer({ dest: './public/' }).any())// 通过配置multer的dest属性, 将文件储存在项目下的tmp文件中
app.get('/index.html', function(req, res){// 访问index.html页面因为不知道本地
res.sendFile(__dirname + '/index.html')
})
app.post('/处理路由url', function(req, res){// 上传接口
let old = req.files[0].path //获取path: 'public\\upload\\0f625978d5d1a783b12e149718f8b634',
let name = req.files[0].path + path.parse(req.files[0].originalname).ext
fs.renameSync(old, name)
res.json({//返回保存的图片名称
'imgpath':name
});
})
const server = app.listen(3000, function(){
console.log('服务器已经启动成功')
})
请求发送成功
我们的文件