1

I want to upload different images from different folders in a single file upload form submit. When I click the upload button for the second time before clicking the submit button, file input field get replace with the latest selections.

Is it possible to append the selections till the submit is clicked.

enter image description here

My JS code displays all the selected file. But submits only the last selections

Here is my HTML

<form name="status-form" id="status-form" method="post" enctype="multipart/form-data">
   <input type='file' name='file1[]' id="upload-image" multiple />
   <input type='hidden' name='file2' value="aaaaaaaa" />
   <div id="upload-img">
     <output id="list"></output>
   </div>
   <br/>  
   <button type="submit" name="submit" class="btn btn-info" id="status-btn">Send It!</button>
</form>

Here is my JS

var allImages = [];
if (window.FileReader) {
  document.getElementById('upload-image').addEventListener('change', handleFileSelect, false);
}

function handleFileSelect(evt) {
   var files = evt.target.files;

   for (var i = 0; i < files.length; i++) {
       var f = files[i];
       var reader = new FileReader();
       reader.onload = (function(f) {
           return function(e) {
               document.getElementById('list').innerHTML = document.getElementById('list').innerHTML + ['<img src="', e.target.result,'" title="', f.name, '" width="150" class="image-gap" />'].join('');
           };
       })(f);
     reader.readAsDataURL(f);
   }

   var formData = $('form').serializeArray(); 
   console.log(formData);

   $.ajax({
       type:'POST',
       url: 'temp.php',
       data:formData,
       success:function(data){
           //code here
       },
       error: function(data){
           //code here
       }
   });
   console.log(folder);

   $('#upload-img').addClass('image-div');
}

And my PHP is just a var_dump for the moment

if (isset($_POST['submit'])) {
   var_dump($_FILES['file1']);
   var_dump($_POST['file2']);
}
4
  • do you mean that 3 files part?? Commented Nov 24, 2015 at 4:44
  • Can you share your code? Commented Nov 24, 2015 at 4:46
  • I want to send all the 5 images. First I selected the first 2 in one folder. then again click on the "Choose File" button and selected the next three in another folder. Now I want to send all 5. Commented Nov 24, 2015 at 4:46
  • @AmitRajput Ok I'll add my code. But other than the simple form submit, there are no any other different codes. I tried few methods to store the details in JS arrays and later pass using Ajax. but failed. Commented Nov 24, 2015 at 4:50

2 Answers 2

1

You can try this:

  • Select file using browse field
  • call a method (setImage()) on onchange of this browse field

and in setImage():

function setImage(){
 // Get the src value of browse field
 // Create a new hidden browse field with src value of above browse 
 // field
 // And set blank value of src of first one browse field
}

The idea is you select an image n times, the above method will create n hidden browse field in your html.

For example: If you select three images, then there will be four browse fields.

  • 1 Shown to you
  • Other three are hidden

Now press submit and in server side you will get 4 file fields one with empty file and other three with files.

Ignore empty one and upload other three images.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I'll try this method and see.
0

With the hint given by Rahul I was able to make it work. Here is the answer

JS File

var uploadImage = 0;

$( document ).ready(function() {
    uploadImage = Math.floor(Date.now() / 1000);
});

if (window.FileReader) {
  document.getElementById('upload-image').addEventListener('change', handleFileSelect, false);
}

function handleFileSelect(evt) {
    var files = evt.target.files;

    for (var i = 0; i < files.length; i++) {
        var f = files[i];
        var reader = new FileReader();
        reader.onload = (function(f) {
            return function(e) {
                document.getElementById('list').innerHTML = document.getElementById('list').innerHTML + ['<img src="', e.target.result,'" title="', f.name, '" width="150" class="image-gap" />'].join('');
                $('<input>').attr({
                    type: 'hidden',
                    id: uploadImage++,
                    name: uploadImage++,
                    value: e.target.result
                }).appendTo('form');
                console.log(e.target.result);
            };
        })(f);
      reader.readAsDataURL(f);
    }

    $('#upload-img').addClass('image-div');
}

PHP Code

if (isset($_POST['submit'])) {
    define('UPLOAD_DIR', 'images/');
    $patterns = array('/data:image\//', '/;base64/');

    foreach ($_POST as $key => $value) {
      if (preg_match('/^(0|[1-9][0-9]*)$/', $key)) {
        $imageData = explode(',', $value, 2);
        $type = preg_replace($patterns, '', $imageData[0]);;
        if (count($imageData) > 1) {
            $img = str_replace($imageData[0].',', '', $value);
            $img = str_replace(' ', '+', $img);
            $data = base64_decode($img);
            $file = UPLOAD_DIR . uniqid() . '.'.$type;
            $success = file_put_contents($file, $data);
            print $success ? $file : 'Unable to save the file.';
        }

      }
    }
}

HTML Code

<form name="status-form" id="status-form" method="post" enctype="multipart/form-data">
    <input type='file' name='file1[]' id="upload-image" multiple />
    <div id="upload-img">
        <output id="list"></output>
    </div>
    <br/>
    <button type="submit" name="submit" class="btn btn-info" id="status-btn">Send It!</button>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.