打算前端传文件给后端node,前端使用formdata,尝试使用koa的multer包来做,但是老是报错,
MulterError: Unexpected field
在网上找了半天,不知道怎么直接用node(不用框架和第三方包)从request中解析出来文件,所以自己想了个方法变换一下来做,很简单,特此记录。
「Talk is cheap. Show me the code」
0 前端代码
<input type="file" onchange="sendFiles(this.files)">
<script>
function sendFiles(files) {
const reader = new FileReader();
const file = files[0];
reader.readAsArrayBuffer(file);
reader.onload = function (e) {
fetch("http://127.0.0.1:3000/" + file.name, {
method: 'post',
body: e.target.result
});
};
}
</script>
1 后端代码
const http = require('http');
const fs = require('fs');
http.createServer(function (request, response) {
response.setHeader('Access-Control-Allow-Origin', '*');
console.log();
request.pipe(fs.createWriteStream('.' + request.url, {
// encoding:'binary' // 行
// encoding:'base64' // 行
// encoding:'utf8' // 不知道为什么,这里怎么设置都不影响,
}));
response.end(`${request.url} done!`);
}).listen(3000);

参考文献:
1、https://stackoverflow.com/questions/14551608/list-of-encodings-that-node-js-supports
2、https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications
3、https://stackoverflow.com/questions/7431365/filereader-readasbinarystring-to-upload-files
本文介绍了一种不依赖框架和第三方包的方法,从前端直接将文件以FormData形式发送到Node.js后端服务器,并在后端进行解析和保存。通过Fetch API和FileReader API读取文件内容,再由Node.js的http模块接收并写入到本地。

1428

被折叠的 条评论
为什么被折叠?



