简体   繁体   English

HTML5多文件上传:使用JavaScript设置文件名吗?

[英]HTML5 Multiple File Upload: Set Filenames with JavaScript?

An HTML form that allows uploading multiple files looks like this: 允许上传多个文件的HTML表单如下所示:

<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? 如何使用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? 可能带有一些html multipart mime send功能?

The append() method of FormData accepts a third optional filename parameter. FormData的append()方法接受第三个可选的文件名参数。 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>

No , we can't set file names by JavaScript for obvious security reasons . ,出于明显的安全原因 ,我们无法通过JavaScript设置文件名。 JS simply is not allowed to do that. JS根本不允许这样做。 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. 但是,您可以上传在服务器上进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM