最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to delete the specific value of an “input type=file” multiple - Stack Overflow

programmeradmin1浏览0评论

I am using input type='file' with multiple file and one with single file. like,

//single image
//IMAGE_TYPES is constant and defined with:define('IMAGE_TYPES',array('main','floor','bedroom1','bedroom2','bedroom3','kitchen','reception','garages','epc','other'));
@foreach(IMAGE_TYPES as $images)
    @if($images!='other')
    <div class="col-sm-10">
        <input type="file" class="form-control" id="{{$images}}_image" name="{{$images}}_image" accept="image/*" placeholder="<span> <i class='fa fa-plus-circle'></i>Click here or drop files to upload</span>"/>
    </div>
    @else
    //multiple
    <div class="col-sm-10">
        <input type="file" class="form-control" id="other_images" name="other_images[]" accept="image/*" placeholder="<span> <i class='fa fa-plus-circle'></i>Click here or drop files to upload</span>" multiple />
    </div>
    @endif
@endforeach

Now, I validating it with jquery like,

var image_type ='<?=json_encode(IMAGE_TYPES);?>';
image_type = JSON.parse(image_type);
var max_image_size = 2;
$.each(image_type, function( index, value ) {
  if (value!='other') {
    $('#'+value+'_image').bind('change', function() {
      var a=(this.files[0].size);
      var ValidImageTypes = ["image/jpeg", "image/png"];
      if ($.inArray(this.files[0].type, ValidImageTypes) < 0) {
        show_notification('error','Only .jpg/.jpeg and .png file allowed. Please select other image.');
        var file = document.getElementById(value+'_image');
        file.value = file.defaultValue;
        return false;
      }
      else{
        if (Math.round(a / (1024 * 1024)) > max_image_size) {
          show_notification('error','Image is Greater than '+max_image_size+'MB. Please select smaller image.');
          var file = document.getElementById(value+'_image');
          file.value = file.defaultValue;
          return false;
        }
        else
        {
          preview_main_image(value);//won't matter
        }
     }
    });
  }
  else{
    $('#other_images').bind('change', function() {
      $('div.add_preview').remove();//won't matter
      for (var i = 0; i < $("#other_images").get(0).files.length; i++) { 
        var a=(this.files[i].size);
        var name = this.files[i].name;
        var ValidImageTypes = ["image/jpeg", "image/png"];
        if ($.inArray(this.files[i].type, ValidImageTypes) < 0) {
          show_notification('error','Image '+name+' is Not allowed. Only .jpg/.jpeg and .png file allowed. Please select other image.');
        }
        else{
          if (Math.round(a / (1024 * 1024)) > max_image_size) {
            show_notification('error','Image '+name+' is Greater than '+max_image_size+'MB. Please select smaller image.');
          }
          else
          {
            $('#other_image_preview').append("<div class='col-md-2 p_3 add_preview'><img class='img-responsive' src='"+URL.createObjectURL(event.target.files[i])+"'></div>");//won't matter
            //preview_detail_images(value);
          }
        }
      }
    });
  }
});

Now, my question is when i am using single image if image is not fitting in validation then i delete it's value from input type='file' using, this code

var file = document.getElementById(value+'_image');
file.value = file.defaultValue;
return false;

But when i select multiple image and if any image is not fitting in validation then how can i remove that particular image from input type='file'.

Please help me

I am using input type='file' with multiple file and one with single file. like,

//single image
//IMAGE_TYPES is constant and defined with:define('IMAGE_TYPES',array('main','floor','bedroom1','bedroom2','bedroom3','kitchen','reception','garages','epc','other'));
@foreach(IMAGE_TYPES as $images)
    @if($images!='other')
    <div class="col-sm-10">
        <input type="file" class="form-control" id="{{$images}}_image" name="{{$images}}_image" accept="image/*" placeholder="<span> <i class='fa fa-plus-circle'></i>Click here or drop files to upload</span>"/>
    </div>
    @else
    //multiple
    <div class="col-sm-10">
        <input type="file" class="form-control" id="other_images" name="other_images[]" accept="image/*" placeholder="<span> <i class='fa fa-plus-circle'></i>Click here or drop files to upload</span>" multiple />
    </div>
    @endif
@endforeach

Now, I validating it with jquery like,

var image_type ='<?=json_encode(IMAGE_TYPES);?>';
image_type = JSON.parse(image_type);
var max_image_size = 2;
$.each(image_type, function( index, value ) {
  if (value!='other') {
    $('#'+value+'_image').bind('change', function() {
      var a=(this.files[0].size);
      var ValidImageTypes = ["image/jpeg", "image/png"];
      if ($.inArray(this.files[0].type, ValidImageTypes) < 0) {
        show_notification('error','Only .jpg/.jpeg and .png file allowed. Please select other image.');
        var file = document.getElementById(value+'_image');
        file.value = file.defaultValue;
        return false;
      }
      else{
        if (Math.round(a / (1024 * 1024)) > max_image_size) {
          show_notification('error','Image is Greater than '+max_image_size+'MB. Please select smaller image.');
          var file = document.getElementById(value+'_image');
          file.value = file.defaultValue;
          return false;
        }
        else
        {
          preview_main_image(value);//won't matter
        }
     }
    });
  }
  else{
    $('#other_images').bind('change', function() {
      $('div.add_preview').remove();//won't matter
      for (var i = 0; i < $("#other_images").get(0).files.length; i++) { 
        var a=(this.files[i].size);
        var name = this.files[i].name;
        var ValidImageTypes = ["image/jpeg", "image/png"];
        if ($.inArray(this.files[i].type, ValidImageTypes) < 0) {
          show_notification('error','Image '+name+' is Not allowed. Only .jpg/.jpeg and .png file allowed. Please select other image.');
        }
        else{
          if (Math.round(a / (1024 * 1024)) > max_image_size) {
            show_notification('error','Image '+name+' is Greater than '+max_image_size+'MB. Please select smaller image.');
          }
          else
          {
            $('#other_image_preview').append("<div class='col-md-2 p_3 add_preview'><img class='img-responsive' src='"+URL.createObjectURL(event.target.files[i])+"'></div>");//won't matter
            //preview_detail_images(value);
          }
        }
      }
    });
  }
});

Now, my question is when i am using single image if image is not fitting in validation then i delete it's value from input type='file' using, this code

var file = document.getElementById(value+'_image');
file.value = file.defaultValue;
return false;

But when i select multiple image and if any image is not fitting in validation then how can i remove that particular image from input type='file'.

Please help me

Share Improve this question edited Jun 24, 2018 at 19:15 pegasuspect 1,0315 silver badges15 bronze badges asked Jun 15, 2018 at 7:24 Divyesh JesadiyaDivyesh Jesadiya 9074 gold badges38 silver badges73 bronze badges 1
  • A great plugin for uploads: dropzone.js. – PajuranCodes Commented Jun 25, 2018 at 0:31
Add a ment  | 

4 Answers 4

Reset to default 2 +25

The file will have to e in input element for the input change handler to work. You can validate there and show only valid files in preview, ignoring the invalid ones.

You can check jQuery file uploader: https://blueimp.github.io/jQuery-File-Upload/

You can keep your input invisible over another div which is your preview and show the uploaded files in the div to give the illusion to the user that you are discarding invalid files.

The answer is simple: You can't. Value of files property of an <input type="file"> is a FileList. This one is immutable for security reasons. Also the files property is readonly and you can't construct a FileList.

The best you could do is to a) show a validation error to user and ask him to remove the file; b) ignore the file on processing (e.g. preview, uploading to server).

As @mixable already pointed out in his answer, validation should also be done on backend.

You can just ignore this file type on the server when processing the uploaded files. This is the better solution, because it is more secure. When you rely on JavaScript, it is very easy to send manipulated data to your server and upload filetypes of other images (or even scripts like js, php, ...).

Hi please check out my fiddle. I created a form which can be automatically submitted with valid files.

https://jsfiddle/2ah5r0bj/135/

What I did is basically:

var form = document.getElementById("myAwesomeForm");
var formDataToUpload = new FormData(form);

...

for (var i = 0; i < validFiles.length; i++) {
  formDataToUpload.append("other_images[]", validFiles[i], validFiles[i].name);
}

var xhr = createCORSRequest("POST", "https://httpbin/post");
xhr.send(formDataToUpload);
发布评论

评论列表(0)

  1. 暂无评论