使用 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 code
// 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>
我写了一篇关于此的文章,其中有更多示例:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)