0

An HTML form that allows uploading multiple files looks like this:

<form action="http://somehost.com/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="image" accept="image/*" multiple>
  <input type="submit">
</form>

The user can click the supplied input button and select multiple files to upload.

How can the filenames be set using JavaScript?

Why would you want to do this?

To allow drag'n'drop, for instance. So that when the user drops files from their system onto the form, it can automatically populate the file input field with those files.

Is there a better way?

Possibly with some html multipart mime send function?

1
  • 1
    This article might give you some hints (check the source code) html5demos.com/dnd-upload Commented Oct 13, 2015 at 10:48

2 Answers 2

4

The append() method of FormData accepts a third optional filename parameter. You could:

<input type="file" name="image" accept="image/*" id="fileinput" multiple>
<button onclick="upload()">Upload</button>

<script>
  this.upload = function() {
    var fileInput = document.getElementById('fileinput');
    for (var i = 0; i < fileInput.files.length; i++) {

      var file = fileInput.files[i];
      var xhr = new XMLHttpRequest();
      var fd = new FormData();

      xhr.open("POST", "http://somehost.com/upload", true);    

      fd.append("upload_file", file, 'YOUR_FILENAME_' + file.name);

      xhr.send(fd);

    }
  }

</script>
Sign up to request clarification or add additional context in comments.

Comments

0

No, we can't set file names by JavaScript for obvious security reasons. JS simply is not allowed to do that. This should be done on server-side.

Files will have the names which they already have on the file system (on your local computer). You can, however, change them on server after uploading them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.