Skip to content

Commit 9e6b0fc

Browse files
committed
增加原生上传文件的DEMO
1 parent 041b671 commit 9e6b0fc

7 files changed

Lines changed: 60 additions & 1 deletion

File tree

.DS_Store

2 KB
Binary file not shown.

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
node_modules
1+
node_modules
2+
.DS_Store

WechatAutoReply/.DS_Store

0 Bytes
Binary file not shown.

uploadFiles/原生上传/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# 运行
2+
3+
```js
4+
node server
5+
浏览器打开 index.html 选中文件自动上传
6+
```
7+
8+
# 原理
9+
10+
前端使用blob二进制格式,由于file本身就是继承与blob,配合ajax技术,可以配合post请求,把二进制放进请求体,传输到后端,注意要设置头部,后端也要设置对应的头部处理这种特殊文件格式
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<!DOCTYPE html>
2+
<html>
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<title></title>
7+
</head>
8+
9+
<body>
10+
<p>利用二进制blob,配合node的http和fs模块实现上传文件</p>
11+
<p>后续还可以使用blob.slice方法实现分块上传</p>
12+
<input type="file" id="file" name="logo" />
13+
</body>
14+
<script>
15+
var fileNode = document.getElementById("file");
16+
fileNode.onchange = function () {
17+
var xmlhttp = new XMLHttpRequest();
18+
//设置回调,当请求的状态发生变化时,就会被调用
19+
xmlhttp.onreadystatechange = function () {
20+
//上传成功,返回的文件名,设置到父节点的背景中
21+
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
22+
console.log(xmlhttp.responseText);
23+
}
24+
}
25+
// file继承于blob格式,可以从原型链观察得出,所以file也是一种blob
26+
var blob = fileNode.files[0];
27+
console.log(blob);
28+
//设置请求,true:表示异步
29+
xmlhttp.open("post", "http://localhost:8877", true);
30+
xmlhttp.setRequestHeader('Content-Type', 'application/octet-stream');
31+
//提交请求,可以直接把二进制内容放到请求体里面发送到后端
32+
xmlhttp.send(blob);
33+
//清除掉,否则下一次选择同样的文件就进入不到onchange函数中了
34+
fileNode.value = null;
35+
}
36+
</script>
37+
38+
</html>

uploadFiles/原生上传/pic.png

2.68 KB
Loading

uploadFiles/原生上传/server.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const http = require('http');
2+
const fs = require('fs');
3+
http.createServer((req, res) => {
4+
// 跨域
5+
res.setHeader('Access-Control-Allow-Origin', '*');
6+
// 必须要设置
7+
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
8+
req.pipe(fs.createWriteStream('./pic.png'));
9+
res.end('success');
10+
}).listen(8877);

0 commit comments

Comments
 (0)