0

I am building a simple HTML image uploader. The user can select many images using a file input, and for each image a preview is created.

To send the images to the server I was thinking about attaching an input to each image so that they are automatically sent when the form is submitted. An element would look like this:

<div>
  <input type="file" class="hidden" name="model[images][]">
  <img src="base 64 image">
</div>

The problem is that of course I can't set an arbitrary file for the file input, so what's the simplest solution to send many files from the same form without using a single input?

bukk530
  • 1,858
  • 2
  • 20
  • 30
  • 2
    Since you'll be using a dataURL in order to preview the images, you can just copy each of them into a separate hidden input, uploading each file as the text contained in it. You could then turn them back into files at the other end. I guess you may also wish to send info like the original filesize and name too. I'd construct a JSON string that contained the base64 dataURL of each image along with its original name and size. I'd then upload that JSON string. – enhzflep Aug 22 '15 at 02:18
  • Yes I also thought about this, just wanted to keep it simple on the server side. As I'm using rails it would be nice to upload the input as a file so it is automatically saved as a temporary file on the serever. Of course if it's not possible that will be the only alternative – bukk530 Aug 22 '15 at 02:24
  • See http://stackoverflow.com/q/28856729/ – guest271314 Aug 22 '15 at 02:52

1 Answers1

1

In modern browsers, you can use the FormData object and its append method :

var input  = document.querySelector('input');
var formdata = new FormData();

var nb = 0;
input.onchange= function(e){
    // since we can't write in a fileList, we have to add an index so our server can access each files
    formdata.append('file_'+nb++, this.files[0], this.files[0].name);
    // we also need to keep track of this index
    formdata.append('file_count', nb);
    }
function sendToServer(){
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'script.php');
    xhr.send(formdata);
}

Then in script.php

$file_count = $_POST['file_count'];
for($i=0; $i<$file_count; $i++){
    // Do whatever with your files
    echo $_FILES['file_'.$i]['name'];
    }
Kaiido
  • 123,334
  • 13
  • 219
  • 285