Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change name of uploaded file on client

I have the following.

<form method="post" action="/send" enctype="multipart/form-data">
    <input type="file" name="filename" id="AttachFile">
</form>

I want to change the name of the file the user uploads.

If the user selects "Document.docx" I want to change it to "Bank - Document.docx".

I still want to read the file the user selected, not some other file, just use a different name for it when sending to the server.

I'm working within bounds of an application which doesn't allow control of the server side, so ideally I need to do this on the client. Furthermore I need this to work within the confines of a form.

I have tried variations of the following without success:

document.getElementById("AttachFile").name = "test.txt"
document.getElementById("AttachFile").files = "test.txt"
document.getElementById("AttachFile").value ="test.txt"
like image 419
James Wood Avatar asked Mar 06 '23 15:03

James Wood


1 Answers

You can do it through the File API. We can also use the Blob API to be compatible with Microsoft edge.

var file = document.getElementById("AttachFile").files[0];
var newFile = new File([file], "Bank - Document.docx", {
  type: file.type,
});

Here's a complete example — see comments:

HTML:

<input type="file" id="AttachFile">
<input type="button" id="BtnSend" value="Send">

JavaScript:

document.getElementById("BtnSend").addEventListener("click", function() {
    // Get the file the user picked
    var files = document.getElementById("AttachFile").files;
    if (!files.length) {
        return;
    }
    var file = files[0];
    // Create a new one with the data but a new name
    var newFile = new File([file], "Bank - Document.docx", {
      type: file.type,
    });
    // Build the FormData to send
    var data = new FormData();
    data.set("AttachFile", newFile);
    // Send it
    fetch("/some/url", {
        method: "POST",
        body: data
    })
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        }
        return response.text(); // or response.json() or whatever
    })
    .then(response => {
        // Do something with the response
    })
    .catch(error => {
        // Do something with the error
    });
});
like image 181
man tou Avatar answered Mar 09 '23 00:03

man tou