Skip to content

Commit 750ecf3

Browse files
committed
补充多文件上传
1 parent c6b638e commit 750ecf3

6 files changed

Lines changed: 57 additions & 0 deletions

File tree

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);
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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" multiple />
13+
</body>
14+
<script>
15+
var fileNode = document.getElementById("file");
16+
fileNode.onchange = function () {
17+
var blobs = fileNode.files;
18+
var length = fileNode.files.length;
19+
for (let index = 0; index < length; index++) {
20+
console.log(blobs[index].name);
21+
let xmlhttp = new XMLHttpRequest();
22+
xmlhttp.onreadystatechange = function () {
23+
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
24+
console.log(xmlhttp.responseText);
25+
}
26+
}
27+
xmlhttp.open(`POST`, `http://localhost:8877?name=${blobs[index].name}`, true);
28+
xmlhttp.setRequestHeader('Content-Type', 'application/octet-stream');
29+
//提交请求,可以直接把二进制内容放到请求体里面发送到后端
30+
xmlhttp.send(blobs[index]);
31+
}
32+
fileNode.value = null;
33+
}
34+
</script>
35+
36+
</html>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
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+
let name = req.url.split('=')[1];
9+
req.pipe(fs.createWriteStream(`./${name}`));
10+
res.end('success');
11+
}).listen(8877);

0 commit comments

Comments
 (0)