项目目录
前端页面 index.html
<!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>
body {
text-align: center;
padding-top: 30px;
}
iframe {
display: block;
margin: 30px auto;
width: 500px;
height: 300px;
}
</style>
</head>
<body>
<input type="file" id="file">
<button onclick="upload()">点击上传</button>
<iframe src="" frameborder="0" id="iframe"></iframe>
<script>
const file = document.querySelector('#file');
const iframe = document.querySelector('#iframe');
function upload() {
const fileData = file.files[0];
if (!fileData) {
alert('请先上传文件!');
return;
}
let formData = new FormData();
formData.append('file', fileData)
fetch('http://localhost:8083/upload', {
method: 'post',
body: formData
}).then(res => res.json()).then(res => {
if (res.code === '0') {
iframe.src = res.url;
}
})
}
</script>
</body>
</html>
后端页面需要安装 express 和 multer 两个模块
npm init -y
npm i express multer -S
index.js
const express = require("express");
const multer = require("multer");
const fs = require("fs");
const app = express();
//实例化multer,传递的参数对象,dest表示上传文件的存储路径
let objMulter = multer({ dest: "./public" });
app.use(objMulter.any()); //any表示任意类型的文件
// app.use(objMulter.image())//仅允许上传图片类型
app.use(express.static("./"));
app.use(express.static("./public"));
app.post("/upload", (req, res) => {
// console.log(req.files);
let oldName = req.files[0].path;
let newName = req.files[0].path + req.files[0].originalname;
//修改名字
fs.renameSync(oldName, newName);
res.send({
code: '0',
url: "http://localhost:8083/" + newName
});
});
app.listen(8083, "localhost", () => {
console.log("点击打开:http://localhost:8083");
});
运行 node index.js
然后访问 http://localhost:8083/
效果图: