148

私は HTML5 を使用してドラッグ アンド ドロップでアップロードする Web アプリケーションを構築しています。ファイルを div にドロップし、もちろん dataTransfer オブジェクトを取得しています。これにより、FileListが得られます。

今、いくつかのファイルを削除したいのですが、方法がわかりませんし、可能かどうかさえわかりません。

できれば、FileList からそれらを削除したいだけです。私は彼らに用がありません。しかし、それが不可能な場合は、代わりに FileList とやり取りするコードにチェックを記述する必要がありますか? 面倒そうです。

4

17 に答える 17

187

選択したファイルのいくつかだけを削除したい場合: できません。リンク先のFile API Working Draftには、次のメモが含まれています。

HTMLInputElementインターフェイス [HTML5] にはreadonly属性 FileListがあります […]
[強調鉱山]

HTML 5 Working Draft を少し読んでいると、 Common inputelement APIsに出くわしました。次のように、オブジェクトのプロパティを空の文字列に設定することで、ファイル リスト全体を削除できるようです。valueinput

document.getElementById('multifile').value = "";

ところで、Using files from web applicationsの記事も興味深いかもしれません。

于 2010-07-01T23:11:38.547 に答える
34

この質問には既に回答済みのマークが付いていますが、他のユーザーが FileList を使用する際に役立つ情報を共有したいと思います。

FileList を配列として扱うと便利ですが、sort、shift、pop、slice などのメソッドは機能しません。他の人が示唆しているように、FileList を配列にコピーできます。ただし、ループを使用するのではなく、この変換を処理する単純な 1 行のソリューションがあります。

 // fileDialog.files is a FileList 

 var fileBuffer=[];

 // append the file list to an array
 Array.prototype.push.apply( fileBuffer, fileDialog.files ); // <-- here

 // And now you may manipulated the result as required

 // shift an item off the array
 var file = fileBuffer.shift(0,1);  // <-- works as expected
 console.info( file.name + ", " + file.size + ", " + file.type );

 // sort files by size
 fileBuffer.sort(function(a,b) {
    return a.size > b.size ? 1 : a.size < b.size ? -1 : 0;
 });

FF、Chrome、IE10+でテスト済み

于 2015-11-29T01:31:28.650 に答える
26

エバーグリーン ブラウザー (Chrome、Firefox、Edge、ただし Safari 9 以降でも動作します) をターゲットにしている場合、またはポリフィルを使用する余裕がある場合は、次のArray.from()ように使用して FileList を配列に変換できます。

let fileArray = Array.from(fileList);

File次に、 s の配列を他の配列と同じように扱うのは簡単です。

于 2016-08-26T09:37:28.667 に答える
14

私たちは HTML5 の領域にいるので、これが私の解決策です。要点は、ファイルを FileList に残すのではなく配列にプッシュし、XHR2 を使用してファイルを FormData オブジェクトにプッシュすることです。以下の例。

Node.prototype.replaceWith = function(node)
{
    this.parentNode.replaceChild(node, this);
};
if(window.File && window.FileList)
{
    var topicForm = document.getElementById("yourForm");
    topicForm.fileZone = document.getElementById("fileDropZoneElement");
    topicForm.fileZone.files = new Array();
    topicForm.fileZone.inputWindow = document.createElement("input");
    topicForm.fileZone.inputWindow.setAttribute("type", "file");
    topicForm.fileZone.inputWindow.setAttribute("multiple", "multiple");
    topicForm.onsubmit = function(event)
    {
        var request = new XMLHttpRequest();
        if(request.upload)
        {
            event.preventDefault();
            topicForm.ajax.value = "true";
            request.upload.onprogress = function(event)
            {
                var progress = event.loaded.toString() + " bytes transfered.";
                if(event.lengthComputable)
                progress = Math.round(event.loaded / event.total * 100).toString() + "%";
                topicForm.fileZone.innerHTML = progress.toString();
            };
            request.onload = function(event)
            {
                response = JSON.parse(request.responseText);
                // Handle the response here.
            };
            request.open(topicForm.method, topicForm.getAttribute("action"), true);
            var data = new FormData(topicForm);
            for(var i = 0, file; file = topicForm.fileZone.files[i]; i++)
                data.append("file" + i.toString(), file);
            request.send(data);
        }
    };
    topicForm.fileZone.firstChild.replaceWith(document.createTextNode("Drop files or click here."));
    var handleFiles = function(files)
    {
        for(var i = 0, file; file = files[i]; i++)
            topicForm.fileZone.files.push(file);
    };
    topicForm.fileZone.ondrop = function(event)
    {
        event.stopPropagation();
        event.preventDefault();
        handleFiles(event.dataTransfer.files);
    };
    topicForm.fileZone.inputWindow.onchange = function(event)
    {
        handleFiles(topicForm.fileZone.inputWindow.files);
    };
    topicForm.fileZone.ondragover = function(event)
    {
        event.stopPropagation();
        event.preventDefault();
    };
    topicForm.fileZone.onclick = function()
    {
        topicForm.fileZone.inputWindow.focus();
        topicForm.fileZone.inputWindow.click();
    };
}
else
    topicForm.fileZone.firstChild.replaceWith(document.createTextNode("It's time to update your browser."));
于 2012-09-19T21:54:23.837 に答える
6

これは古い質問ですが、この問題に関して検索エンジンで上位にランクされています。

FileListオブジェクトのプロパティは削除できませんが、少なくとも Firefox では変更できますIsValid=trueこの問題の回避策は、チェックに合格したファイルと合格IsValid=falseしなかったファイルにプロパティを追加することでした。

次に、リストをループして、 を持つプロパティのみがFormDataIsValid=trueに追加されるようにします。

于 2015-06-15T03:48:12.727 に答える
2

これは一時的なものですが、この方法で解決したのと同じ問題がありました。私の場合、XMLHttp リクエスト経由でファイルをアップロードしていたので、formdata の追加によって FileList のクローン データを投稿できました。機能は、複数のファイルを何度でもドラッグ アンド ドロップまたは選択できることです (ファイルを再度選択しても、複製された FileList はリセットされません)。(複製された) ファイル リストから必要なファイルを削除し、xmlhttprequest を介して送信します。そこに残しました。これが私がしたことです。これは私の最初の投稿なので、コードは少し面倒です。ごめん。ああ、Joomla スクリプトのように、$ の代わりに jQuery を使用する必要がありました。

// some global variables
var clon = {};  // will be my FileList clone
var removedkeys = 0; // removed keys counter for later processing the request
var NextId = 0; // counter to add entries to the clone and not replace existing ones

jQuery(document).ready(function(){
    jQuery("#form input").change(function () {

    // making the clone
    var curFiles = this.files;
    // temporary object clone before copying info to the clone
    var temparr = jQuery.extend(true, {}, curFiles);
    // delete unnecessary FileList keys that were cloned
    delete temparr["length"];
    delete temparr["item"];

    if (Object.keys(clon).length === 0){
       jQuery.extend(true, clon, temparr);
    }else{
       var keysArr = Object.keys(clon);
       NextId = Math.max.apply(null, keysArr)+1; // FileList keys are numbers
       if (NextId < curFiles.length){ // a bug I found and had to solve for not replacing my temparr keys...
          NextId = curFiles.length;
       }
       for (var key in temparr) { // I have to rename new entries for not overwriting existing keys in clon
          if (temparr.hasOwnProperty(key)) {
             temparr[NextId] = temparr[key];
             delete temparr[key];
                // meter aca los cambios de id en los html tags con el nuevo NextId
                NextId++;
          }
       } 
       jQuery.extend(true, clon, temparr); // copy new entries to clon
    }

// modifying the html file list display

if (NextId === 0){
    jQuery("#filelist").html("");
    for(var i=0; i<curFiles.length; i++) {
        var f = curFiles[i];
        jQuery("#filelist").append("<p id=\"file"+i+"\" style=\'margin-bottom: 3px!important;\'>" + f.name + "<a style=\"float:right;cursor:pointer;\" onclick=\"BorrarFile("+i+")\">x</a></p>"); // the function BorrarFile will handle file deletion from the clone by file id
    }
}else{
    for(var i=0; i<curFiles.length; i++) {
        var f = curFiles[i];
        jQuery("#filelist").append("<p id=\"file"+(i+NextId-curFiles.length)+"\" style=\'margin-bottom: 3px!important;\'>" + f.name + "<a style=\"float:right;cursor:pointer;\" onclick=\"BorrarFile("+(i+NextId-curFiles.length)+")\">x</a></p>"); // yeap, i+NextId-curFiles.length actually gets it right
    }        
}
// update the total files count wherever you want
jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
    });
});

function BorrarFile(id){ // handling file deletion from clone
    jQuery("#file"+id).remove(); // remove the html filelist element
    delete clon[id]; // delete the entry
    removedkeys++; // add to removed keys counter
    if (Object.keys(clon).length === 0){
        jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
        jQuery("#fileToUpload").val(""); // I had to reset the form file input for my form check function before submission. Else it would send even though my clone was empty
    }else{
        jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
    }
}
// now my form check function

function check(){
    if( document.getElementById("fileToUpload").files.length == 0 ){
        alert("No file selected");
        return false;
    }else{
        var _validFileExtensions = [".pdf", ".PDF"]; // I wanted pdf files
        // retrieve input files
        var arrInputs = clon;

       // validating files
       for (var i = 0; i < Object.keys(arrInputs).length+removedkeys; i++) {
         if (typeof arrInputs[i]!="undefined"){
           var oInput = arrInputs[i];
           if (oInput.type == "application/pdf") {
               var sFileName = oInput.name;
               if (sFileName.length > 0) {
                   var blnValid = false;
                   for (var j = 0; j < _validFileExtensions.length; j++) {
                     var sCurExtension = _validFileExtensions[j];
                     if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                       blnValid = true;
                       break;
                     }
                   }
                  if (!blnValid) {
                    alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                    return false;
                  }
              }
           }else{
           alert("Sorry, " + arrInputs[0].name + " is invalid, allowed extensions are: " + _validFileExtensions.join(" or "));
           return false;
           }
         }
       }

    // proceed with the data appending and submission
    // here some hidden input values i had previously set. Now retrieving them for submission. My form wasn't actually even a form...
    var fecha = jQuery("#fecha").val();
    var vendor = jQuery("#vendor").val();
    var sku = jQuery("#sku").val();
    // create the formdata object
    var formData = new FormData();
    formData.append("fecha", fecha);
    formData.append("vendor", encodeURI(vendor));
    formData.append("sku", sku);
    // now appending the clone file data (finally!)
    var fila = clon; // i just did this because I had already written the following using the "fila" object, so I copy my clone again
    // the interesting part. As entries in my clone object aren't consecutive numbers I cannot iterate normally, so I came up with the following idea
    for (i = 0; i < Object.keys(fila).length+removedkeys; i++) { 
        if(typeof fila[i]!="undefined"){
            formData.append("fileToUpload[]", fila[i]); // VERY IMPORTANT the formdata key for the files HAS to be an array. It will be later retrieved as $_FILES['fileToUpload']['temp_name'][i]
        }
    }
    jQuery("#submitbtn").fadeOut("slow"); // remove the upload btn so it can't be used again
    jQuery("#drag").html(""); // clearing the output message element
    // start the request
    var xhttp = new XMLHttpRequest();
    xhttp.addEventListener("progress", function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
        }, false);
        if ( xhttp.upload ) {
            xhttp.upload.onprogress = function(e) {
                var done = e.position || e.loaded, total = e.totalSize || e.total;
                var percent = done / total;
                jQuery("#drag").html(Math.round(percent * 100) + "%");
            };
        }
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
         var respuesta = this.responseText;
         jQuery("#drag").html(respuesta);
        }
      };
      xhttp.open("POST", "your_upload_handler.php", true);  
      xhttp.send(formData);
    return true;
    }
};

これで、html とスタイルが作成されました。私はかなりの初心者ですが、これはすべて実際にうまくいき、理解するのに時間がかかりました.

<div id="form" class="formpos">
<!--    Select the pdf to upload:-->
  <input type="file" name="fileToUpload[]" id="fileToUpload" accept="application/pdf" multiple>
  <div><p id="drag">Drop your files here or click to select them</p>
  </div>
  <button id="submitbtn" onclick="return check()" >Upload</button>
// these inputs are passed with different names on the formdata. Be aware of that
// I was echoing this, so that's why I use the single quote for php variables
  <input type="hidden" id="fecha" name="fecha_copy" value="'.$fecha.'" />
  <input type="hidden" id="vendor" name="vendorname" value="'.$vendor.'" />
  <input type="hidden" id="sku" name="sku" value="'.$sku.'"" />
</div>
<h1 style="width: 500px!important;margin:20px auto 0px!important;font-size:24px!important;">File list:</h1>
<div id="filelist" style="width: 500px!important;margin:10px auto 0px!important;">Nothing selected yet</div>

そのためのスタイル。Joomla の動作をオーバーライドするために、それらのいくつかを !important とマークする必要がありました。

.formpos{
  width: 500px;
  height: 200px;
  border: 4px dashed #999;
  margin: 30px auto 100px;
 }
.formpos  p{
  text-align: center!important;
  padding: 80px 30px 0px;
  color: #000;
}
.formpos  div{
  width: 100%!important;
  height: 100%!important;
  text-align: center!important;
  margin-bottom: 30px!important;
}
.formpos input{
  position: absolute!important;
  margin: 0!important;
  padding: 0!important;
  width: 500px!important;
  height: 200px!important;
  outline: none!important;
  opacity: 0!important;
}
.formpos button{
  margin: 0;
  color: #fff;
  background: #16a085;
  border: none;
  width: 508px;
  height: 35px;
  margin-left: -4px;
  border-radius: 4px;
  transition: all .2s ease;
  outline: none;
}
.formpos button:hover{
  background: #149174;
  color: #0C5645;
}
.formpos button:active{
  border:0;
}

これが役立つことを願っています。

于 2018-03-06T02:46:32.873 に答える
0

これはかなり古い質問だと思いますが、送信前にカスタム UI で選択的に削除できる任意の数のファイルをキューに入れるために、html 複数ファイル選択アップロードを使用しています。

次のようにファイルを変数に保存します。

let uploadedFiles = [];

//inside DOM file select "onChange" event
let selected = e.target.files[0] ? e.target.files : [];
uploadedFiles = [...uploadedFiles , ...selected ];
createElements();

「ファイルの削除」で UI を作成します。

function createElements(){
  uploadedFiles.forEach((f,i) => {

    //remove DOM elements and re-create them here
    /* //you can show an image like this:
    *  let reader = new FileReader();
    *  reader.onload = function (e) {
    *    let url = e.target.result;
    *    // create <img src=url />
    *  };
    *  reader.readAsDataURL(f);
    */

    element.addEventListener("click", function () {
      uploadedFiles.splice(i, 1);
      createElements();
    });

  }
}

サーバーに送信:

let fd = new FormData();
uploadedFiles.forEach((f, i) => {
  fd.append("files[]", f);
});
fetch("yourEndpoint", { 
  method: "POST", 
  body: fd, 
  headers: { 
    //do not set Content-Type 
  } 
}).then(...)
于 2020-11-18T17:47:52.060 に答える
-1

私はこの方法で解決します

 //position  -> the position of the file you need to delete

  this.fileImgs.forEach((item, index, object) => {
     if(item.idColor === idC){
        if(item.imgs.length === 1){
            object.splice(index,1) }
        else{
           const itemFileImgs = [...item.imgs];
           itemFileImgs.splice(position,1)
           item.imgs = [...itemFileImgs] 
            }
        }});
      console.log(this.fileImgs)

ここに画像の説明を入力

于 2021-06-24T22:28:44.927 に答える
-1

配列を作成し、読み取り専用のファイルリストの代わりにそれを使用したい場合があります。

var myReadWriteList = new Array();
// user selects files later...
// then as soon as convenient... 
myReadWriteList = FileListReadOnly;

その後、組み込みのリストではなく、リストに対してアップロードを行います。あなたが作業しているコンテキストはわかりませんが、見つけたjqueryプラグインを使用しています。プラグインのソースを取得して、<script>タグを使用してページに配置する必要がありました。次に、ソースの上に配列を追加して、グローバル変数として機能し、プラグインが参照できるようにしました。

次に、参照を交換するだけの問題でした。

これにより、ドラッグ アンド ドロップも追加できると思います。ビルトイン リストが読み取り専用の場合、ドロップされたファイルをリストに追加するにはどうすればよいでしょうか。

:))

于 2011-03-23T20:06:22.700 に答える