The question is the following, using the <input type="file"> we select the file, and after clicking the button we send it to the server, so before sending it to the server, we would like to give it a new name and send it with a new name it to the server.

 function onChangeFile(e) { var eventData = e.dataTransfer || e.target; var files = eventData.files; for (var i = 0, file; file = files[i]; i++) { file[i].name = 'new-name-' + i + '.txt'; // расширение не важно... } //... тут дальше код обработки и отправки } 
  • Rename or make a copy with a new one. And then send. - Sergey

1 answer 1

I can offer through FormData

Which has an append method that can take two or three parameters. In the case of three parameters, it will look like this: formData.append(name, value, filename); where as the third parameter is what is needed

filename - The name of the file that will be sent to the server (USVString) when Blob or File passed the test as the second parameter. The default filename for Blob objects is "blob".

Minimum example:

 $(document).on('click', '#btn', function(){ var formData = new FormData(); formData.append("myFile", document.getElementById("file").files[0], 'chris1.jpg'); var xhr = new XMLHttpRequest(); xhr.open("POST", "index.php"); xhr.send(formData); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="post" enctype="multipart/form-data" action=""> <input type="button" id="btn" value="GO" /> <input type="file" id="file" name="file" /> 

As a result, the following will fly to the server:

 Content-Disposition: form-data; name="myFile"; filename="test.jpg" Content-Type: image/jpeg 

That is a picture with the name test.gpg

Make sure that this is true - you can php banal print_r($_FILES) in php and get:

 Array ( [myFile] => Array ( [name] => test.jpg [type] => image/jpeg [tmp_name] => W:\userdata\temp\php7731.tmp [error] => 0 [size] => 875248 ) ) 
  • IE 10 +? .......... - Jean-Claude