ajax 发送 formdata,用 formidable 来处理接收的数据,然后存到本地; 用 axios 发送的请求,可以正常运行,但是用原生 ajax 的就无效,是哪里写错了吗
<div id="app">
<input type="file" name="" id="fileSelect" />
<button type="submit" id="fileUpload">fileUpload</button>
</div>
<script>
const fileSelect = document.getElementById('fileSelect');
const fileUpload = document.getElementById('fileUpload');
fileUpload.addEventListener('click', picUpload);
function picUpload() {
let formdata = new FormData();
console.log('filelist: ', fileSelect.files);
formdata.append('myfile', fileSelect.files[0]);
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://127.0.0.1:3000', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(formdata);
}
</script>
const http = require('http'),
formidable = require('formidable');
path = require('path');
const server = http.createServer(function (req, res) {
if (req.method.toLowerCase() === 'post') {
const form = formidable({
multiples: true,
uploadDir: path.resolve(__dirname, 'upload'),
});
form.parse(req, (err, fields, files) => {
console.log('fields:', fields);
console.log('files:', files);
res.writeHead(200, {
'content-type': 'application/json',
'Access-Control-Allow-Origin': '*',
});
res.end(JSON.stringify({ fields, files }, null, 2));
});
return;
}
res.writeHead(200, {
'content-type': 'text/html',
'Access-Control-Allow-Origin': '*',
});
res.end('Done!');
});
server.listen(3000);
打印出来 fields 和 files 都是空的
1
jay4497 2021-05-11 16:13:54 +08:00
把 setRequestHeader 那行去掉就行了。
developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects 这里有段 warning 好像说的是这个。 |