1

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();
        });
    }

1 Answers1

0

From what I know about HTML, I would say that it would be mostly in your HTML rather than your server. If you can access the file by typing in the path to the file after the domain in the URL, then you should be able to access it via the website.

A simple HTML example of this would look like this:

<a href="path/to/file.js" download>

You could then style the link with CSS to look however you want it to.

ZachT112
  • 31
  • 5