javascript - Change name File selected by input type file - Stack Overflow

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

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=".1.1/jquery.min.js"></script>
<input id='FileID' class='class1' type='file' name='Images' value='' />

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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='FileID' class='class1' type='file' name='Images' value='' />

Share Improve this question edited Jul 17, 2017 at 9:55 Satpal 133k13 gold badges167 silver badges170 bronze badges asked Jul 17, 2017 at 9:53 majid_shoorabimajid_shoorabi 1291 gold badge1 silver badge17 bronze badges 5
  • You cannot change the filename from JS. Assuming that your goal is to save the file with a different name on the server, you will have to do that to the copy you receive on the server when the request is sent – Rory McCrossan Commented Jul 17, 2017 at 9:55
  • You can't change the filename by using js. If you change the filename using js it may cause to generate an error (file not found or something like that) after form submission. You can rename the file at the time of uploading in destination folder, depend on what programming language do you use. – Ankit Singh Commented Jul 17, 2017 at 10:06
  • Question: why do you want to change the input type=file's file name? What are you trying to achieve by changing this? Sounds like an XY Problem The reason it's blocked is for security, to stop malicious websites doing something like: - set file to c:\password.txt - upload file - in a hidden iframe. – fdomn-m Commented Jul 17, 2017 at 10:14
  • @raptor, what is the purpose behind renaming? BTW, files can be renamed on server side as well. – user2575725 Commented Jul 17, 2017 at 11:11
  • This link might help you: stackoverflow./a/48453136/1666800 – Vahid Farahmandian Commented Jan 25, 2018 at 22:49
Add a ment  | 

2 Answers 2

Reset to default 3

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./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 remend 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.

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);
  };
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742314397a4420545.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信