我真的不知道如何将图像发送到我的服务器,然后将其保存在文件夹中。我试图将图像解码为base64和许多其他方式,但我仍然无法正确发送它然后将图像渲染到文件。请帮忙..
这是我的代码..
<body>
<form id="upload-form">
<input id="file" type="file">
<input id="send-btn" type="button" value="Качи файла">
</form>
<div id="download"></div>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
const formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
const image = new Image(formData);
$('#send-btn').on("click", function () {
$.ajax('', {
method: 'POST',
data: window.btoa(image),
processData: false,
contentType: false,
});
});
</script>
</body>
我的服务器......
const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
if (req.method === 'POST') {
let imageString = '';
req.on('data', function (data) {
imageString += data;
console.log(imageString);
});
req.on('end', function () {
fs.writeFile('image.jpg', imageString, 'base64', (err) => console.log(err));
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('post received');
} else if (req.method === 'GET') {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write(fs.readFileSync('index.html'));
res.end();
}
}).listen(8080, '127.0.0.1');