使用浏览器 firefox 和 chrome
我有一个输入文件元素。
<input type='file' id='tempFileInput' multiple></input>
假设我为上面的文件输入框('tempFileInput')选择了三个文件;
OnChange 我想为每个文件将三个文件分成三个新的文件输入框。 IE
<input type='file' id='inputFile_0'></input>
<input type='file' id='inputFile_1'></input>
<input type='file' id='inputFile_2'></input>
我正在努力实现这一目标。有什么帮助吗?
//我已经为我想要实现的目标编写了一个小的 JavaScript 片段。
var index = 0;
function multipleInputBoxes(tempFileInput){
var divForm = document.getElementById('divForm');
var numOfFiles = tempFileInput.files.length;
for(var i=0; i<numOfFiles; i++){
var newUploader = document.createElement('input');
newUploader.type='file';
newUploader.id = 'inputFile_' + index;
var file = tempFileInput.files[i];
***newUploader.files[0] = file;***
//above line does not work, as by default due to security reasons input type='file' is read only, and non editable.
divForm.appendChild(newUploader);
index++;
}
}
最佳答案
在其他帖子中找到分散的代码并组装了一个工作示例,它将输入文件“多个”文件分解为单个文件,并允许您删除它们或添加新文件而不会丢失先前选择的文件:
JS代码
// Requires jQuery
function addFileToNewInput(file, newInput) {
if (!newInput) { return }
var dataTransfer = new DataTransfer()
dataTransfer.items.add(file)
newInput.files = dataTransfer.files
}
function addFileNameToPreview(file, preview) {
if (!preview) { return }
preview.innerText = file.name
}
function breakIntoSeparateFiles(input, targetSelector, templateSelector) {
var $input = $(input)
var templateHtml = $(templateSelector).html()
if (!input.files) { return }
for(var file of input.files) {
var $newFile = $(templateHtml).appendTo(targetSelector)
addFileToNewInput(file, $newFile.find("input")[0])
addFileNameToPreview(file, $newFile.find(".file-name")[0])
}
$input.val([])
}
HTML
<!-- Requires bootstrap css for style -->
<form class="m-5">
<div id="file-list"></div>
<label for="upload_input" class="btn btn-warning">Upload</label>
<input
id="upload_input"
type="file"
name="post[attachments][]"
class="d-none"
multiple="multiple"
onchange="window.breakIntoSeparateFiles(this, '#file-list', '#file-preview')"
/>
<template id="file-preview">
<div class="file-preview mb-2">
<span class="file-name"></span>
<button
class="btn btn-sm btn-danger ml-2"
onclick="$(this).closest('.file-preview').remove()"
>×</button>
<input class="d-none" multiple="multiple" type="file" name="post[attachments][]">
</div>
</template>
</form>
我为此写了一篇文章,其中有更多示例:https://medium.com/@goncalvesjoao/break-input-file-into-individual-files-and-preview-them-29fdbab925b2
关于javascript - 如何从单个输入中获取多个文件输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10990890/