majid_shoorabi
majid_shoorabi

Reputation: 129

Change name File selected by input type file

I want to change name's file selected by input type=file, but it doesn't work.

This is my code:

$("document").ready(function() {
  $('body').on('change', '#FileID', function() {
    var name = document.getElementById('FileID');
    name.files.item(0).name = Math.floor(Math.random() * 100000);
    console.log('Selected file: ' + name.files.item(0).name);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='FileID' class='class1' type='file' name='Images' value='' />

Upvotes: 3

Views: 14027

Answers (2)

Kaiido
Kaiido

Reputation: 136658

To change the name of a File object, you need to create a new File instance.
You can create one from a previous File object and it will act a simple wrapper over the data on disk.

The sketchier part is to update the <input type="file"> value to use this new File.
It is now possible through an hack as exposed in this answer of mine:

$('body').on('change', '#FileID', function(evt) {
  const newName = Math.floor(Math.random() * 100000);
  const input = evt.currentTarget;
  const previousFile = input.files[0];
  const newFile = new File([previousFile], newName);
  
  // hack to update the selected file
  const dT = new DataTransfer();
  dT.items.add(newFile);
  input.files = dT.files;
  console.log('Selected file: ' + input.files.item(0).name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='FileID' class='class1' type='file' name='Images' value='' />

However since this part is still mainly an hack, I can't really recommend its use.
So if you don't need to show the updated value in the native input, don't do it. Simply update a custom UI, and use a FormData to upload to your server. The last param of FormData#append(blob, fieldname, filename) will set the filename sent by the browser in the form-data request:

const form = new FormData();
const file = new File(["some data"], "originalname.txt");
form.append("fileField", file, Math.floor(Math.random() * 100000));
console.log("original file's name: ", file.name);
new Response(form).text()
  .then((content) => console.log("formdata content: ", content));

So you should not need the aforementioned hacks at all.

Upvotes: 3

Marc Albrand
Marc Albrand

Reputation: 19

For anyone ending here trying to get rid of the file's name, try converting it to base64. this way it won't have the name attached to it and you could upload it how you want. I will leave a code example using reactJS for this.

1: Here is the input file type calling the onChange event with our function:

<input onChange={this.handleBackgroundImagePreview} type="file" accept="image/png,image/gif,image/jpeg"></input>

2: Then convert that image to base64

handleBackgroundImagePreview = (e) =>{
  // Retrieves the selected Image or file
  const file = e.target.files[0]

  //Calling async file reader with a callback
  let fileBase64 = '';
  this.getBase64(file, (result) => {
      fileBase64 = result;
      console.log(fileBase64)
      //In here you could upload to the server the base 64 data as you want
  });
}

getBase64(file, cb) {
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function () {
      cb(reader.result)
  };
  reader.onerror = function (error) {
      console.log('Error: ', error);
  };
}

Upvotes: 0

Related Questions