using post method to transfer data to server without changing url in node. js

467 Views Asked by At

I'm developing a real-time chat application now. I use node.js, ejs template, and Mysql database. I would like to add the "transfer file" function, this is my client-side code.

<form action="/upload" method="POST" enctype="multipart/form-data">
                <input  id = "file" type="file" name="fliename">
                <input  id="upload" type ="submit" value="Upload">
              </form>

This is my server-side code:

.post('/upload',(req,res)=>{if(req.files){console.log(req.files);}}

if I use the post method to get a file from client-side, then the URL will be changed, is there any way to avoid URL changing? I just wanna this post method to save the file to the database. or there are some better solutions can instead? Thanks in advance!

1

There are 1 best solutions below

0
Atlow On

You should block the default form behavior using prevent default, and use js fetch() to send your form data without changing url.

const myForm = document.querySelector("form");
/*BLOCK FORM SUBMIT*/
myForm.addEventListener("submit", e => {
    e.preventDefault();
    return false;
    /*Extract FILE and add it to FormData*/
    const myFormFile = document.querySelector("input#file");
    const file = myFormFile.target.files || myFormFile.dataTransfer.files
    const formData = new FormData();
    if (file.length > 0) {
        formData.append("filename", file[0]);
    }
    /*Now once you've got the FormData, you dhould send it with fetch.*/
        fetch('/post', {
        method: "POST",
        body: formData,
    });
});