The web page is made, it is assembled modularly. I use node js, the node-static server.
I need to implement downloading a file, that is, from a computer and then to the device so that the file is downloaded by the button.
While I’m trying from the computer to my own computer, on the path I need, but it doesn’t work out in any way. Already tried all sorts of npm modules. Here is the html code and the client file where the sending occurs:
<form name="upload" method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file">
<input type="submit" name="submit" value="Обновить">
</form>
fileId = file.name;
var formData = new FormData();
formData.append("file", document.querySelector('input').files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "savesettings", true);
xhr.setRequestHeader('X-File-Id', fileId);
xhr.addEventListener("load", function() {
console.log("Done:", xhr.status);
});
xhr.send(formData);
Here is the script that was supposed to accept the request and save the file to the desired directory, here it seems to me the main problems:
if (req.url == '/savesettings' && req.method == 'POST') {
let fileId = req.headers['x-file-id'];
let filePath = path.join('/home/alexandr/alexandr/web-cfg/uploads', fileId);
if (!uploads[fileId]) uploads[fileId] = {};
let upload = uploads[fileId];
let fileStream;
upload.bytesReceived = 0;
fileStream = fs.createWriteStream(filePath, {
flags: 'w'
});
console.log("fileStream1:", fileStream);
req.on('data', function(data) {
console.log("data:", data.length);
upload.bytesReceived += data.length;
console.log("bytes received", upload.bytesReceived);
});
req.pipe(fileStream);
console.log("req.pipe:", req.pipe(fileStream));
console.log("123", req.data);
fileStream.on('close', function() {
if (upload.bytesReceived <= 50000) {
debug("Upload finished");
delete uploads[fileId];
res.end("Success " + upload.bytesReceived);
} else {
debug("File unfinished, stopped at " + upload.bytesReceived);
res.end();
}
});
fileStream.on('error', function(err) {
debug("fileStream error");
res.writeHead(500, "File error");
res.end();
});
}