I am sending the following form to the Node server:

<form id="test_form" action="http://localhost:8080/upload" method="post" enctype="multipart/form-data"> <input type="file" name="filetoupload"><br> <input type="submit"> </form> 

It is necessary for the server to receive the same thing, but at the same time the page did not reload when the form was submitted. How to implement? Which way to dig?

  • You need ajax. - Alexander
  • Yes, but how can Ajax send the data in the query in exactly the same form as in the current implementation? Otherwise, the request is incorrectly processed on the server. I can not understand what the server receives when sending a request - A. Lakhno
  • Use new FormData - Qwertiy
  • Send to new window ( target="_blank" ) or iframe . You can also just teach the server to respond with code 204, then the page will not reload - Alexey Ten

1 answer 1

 <div> <input type="file" id="filetoupload"><br> <input type="button" id="button" value="button"> </div> <script> document.getElementById('button').onclick = function() { var file = document.getElementById('filetoupload').files[0]; if (file) upload(file); function upload(file) { var xhr = new XMLHttpRequest(); xhr.open("POST", "/upload", true); xhr.send(file); xhr.onload = xhr.onerror = function() { if (this.status == 200) { console.log('Файл загружен'); } else { console.log("error " + this.status); } }; } }; </script> 
  1. You define - send the form or file?
  2. The multipart/formdata exists in nature in order to send different types of data within the same form - binary and text. But they don’t use it, because the request cannot be checked for a cross-site attack - the token is not visible before decoding.
  3. AJAX sends data as a stream (stream), and not as a single packet — appropriately, it must be createStreamWrite via createStreamWrite .
  4. Thanks for attention.
  • In this form, the form is sent to the server? <form id="test_form" action="localhost:8080/upload"; method="post" enctype="multipart/form-data"> <input type="file" name="filetoupload"><br><input type="submit"></form> <form id="test_form" action="localhost:8080/upload"; method="post" enctype="multipart/form-data"> <input type="file" name="filetoupload"><br><input type="submit"></form> In this form, the server accepts the request and everything works correctly. Is it possible to send data using the http request in the same way that it goes to the server with the example I induced? - A. Lakhno