我有一个输入类型文件,我将其放入我想操作文件的 javascript 变量中。
HTML:
<input class="file" id="file1" name="uploadedimages[]" type='file' multiple/>
JavaScript:
var upload = document.getElementById('file1');
upload.files.splice(idtoremove,1) //not working
我如何删除上传变量中的特定项目?我搜索到输入类型文件是只读的,除非将其放入数组并使用 ajax 上传文件,否则您无法操作它。
我这样做是为了上传到我的画廊。首先我选择多张图片。然后在上传之前先对图片进行预览。还有一个选项可以删除照片。我的问题是。我怎样才能删除输入文件中的照片文件。所以可能的解决方案是将输入文件存储到数组然后删除数组中你想要的照片然后为数组创建一个表单数据并使用ajax上传
最佳答案
编辑、更新
how can i delete a specific item in upload variable?
如果预期结果是文件对象数组,将调整从原始 files
对象拼接数组项的方法 - 并将拼接数组作为上传发送 - 而不是尝试从原始 中“删除”项目files
对象并且仍在上传原始files
对象。
FileList对象没有 .splice()
方法。尝试利用 .slice()
, .call()
将 files
转换为 Array
,然后调用
方法,例如;File
对象数组的 .splice()
// `_files` : `File` object items from original `files` `FileList`
// call `.splice()` on items that would be uploaded ,
// upload `_files` array - _not_ original `files` `FileList` object
// e.g.; `_files`:`File` objects to _keep_ not "delete" from `files`
var idstokeep = [0, 2]; // splice , keep first `2` files
var _files = Array.prototype.slice.call(files).splice(idstokeep[0], idstokeep[1]);
参见 how does Array.prototype.slice.call() work?
或者,利用
Returns a File object representing the file at the specified index in the file list.
返回 FileList
中特定 index
处的文件
var files = e.target.files;
// return `file` at `index` `1`
var firstFile = files.item(1);
var upload = document.getElementById("file1");
upload.onchange = function(e) {
var files = e.target.files;
// https://developer.mozilla.org/en-US/docs/Web/API/FileList#item
var firstFile = files.item(1);
var idstokeep = [0, 2]; // keep first `2` files from `multiple` selection
var _files = Array.prototype.slice.call(files).splice(idstokeep[0], idstokeep[1]);
console.log(files, files.length
, _files, _files.length
, firstFile);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input class="file" id="file1" name="uploadedimages[]" type='file' multiple/>
关于javascript - 输入文件到数组 javascript/jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29841147/