想要实现图片上传我们需要知道其中的原理,下面有几个 api 需要大家掌握

FormData

是一个用来保存 form 表单数据的构造器
方法:

  • append
  • delete
  • get
  • getAll
  • keys
  • values
  • entries
  • set
  • has

前端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<!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>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<style>
.upload label {
width: 150px;
height: 150px;
display: inline-block;
text-align: center;
line-height: 150px;
border: 1px solid #ccc;
}
.upload input[type="file"] {
display: none;
}
</style>
</head>
<body>
<div class="upload">
<label for="avatar">请选择图片</label>
<input id="avatar" type="file" onchange="changehandler(this.files)" />
</div>
<script>
const changehandler = function (file) {
const formdata = new FormData();
formdata.append("avatar", file[0]);
upload(formdata);
};
const createImg = function (url, target) {
const oImg = new Image();
oImg.src = url;
target.appendChild(oImg);
};
const upload = async function (formdata) {
const url = "http://localhost:3000/user/upload";
const result = await axios.post(url, formdata);
if (result.status === 200) {
alert(result.data.msg);
const wraper = document.querySelector(".upload");
createImg(result.data.avatar, wraper);
}
};
</script>
</body>
</html>

后端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var fs = require("fs");
var path = require("path");
var app = require("express")();
var multipartMiddleware = require("connect-multiparty")();

app.use(express.static(path.join(__dirname, "public")));

app.post("/user/upload", multipartMiddleware, (req, res) => {
const file = req.files.avatar;
const sourcePath = path.normalize(file.path);
const targetPath = path.join(
process.cwd(),
"public/images/avatar",
file.name
);
const fileContext = fs.readFileSync(sourcePath);
const error = fs.writeFileSync(targetPath, fileContext);

if (!error) {
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
});
res.end(
JSON.stringify({
code: 1,
avatar: `http://localhost:3000/images/avatar/${file.name}`,
msg: "上传成功!",
})
);
}
});