Skip to content
LetsTalkMedia edited this page Apr 4, 2016 · 7 revisions

Contributed by PhilCowart and JaisonErick

Often sending data to the server, along with the file itself, is needed. Using PHP you'll often use the $_FILES global to get the file itself and the $_POST global to get the other fields values. Here are two examples using ng-file-upload to send files to PHP backend scripts.

Sending arrays as fields

Upload.upload({
    url: 'api/upload-image.php', 
    method: 'POST',
    file: file,
    sendFieldsAs: 'form',
    fields: {
        tags: [ 'dark', 'moon' ]
    }
})

This is the same as the following, using pure HTML form:

<input type="text" name="tags[]" />
<input type="text" name="tags[]" />
<input type="file" name="file" />

You can handle the data on the backend like this:

  $filename = $_FILES['file']['name'];
  $tags = $_POST['tags'];  // $tags = array('dark', 'moon');
  $destination = '../assets/img/users/' . $filename;
  move_uploaded_file( $_FILES['file']['tmp_name'] , $destination );

Sending object arrays

Sometimes you need to send multiple objects to the server along with the file itself. Something like this in HTML:

<input type="text" name="contact[0][name]" />
<input type="text" name="contact[0][email]" />
<input type="text" name="contact[1][name]" />
<input type="text" name="contact[1][email]" />
<input type="file" name="file" />

Would be like this, using ng-file-upload:

Upload.upload({
    url: 'api/upload-image.php', 
    method: 'POST',
    file: file,
    sendFieldsAs: 'form',
    fields: {
        contact: [
            { name: 'John', email: '[email protected]' },
            { name: 'Linda', email: '[email protected]' }
        ]
    }
})

You can handle the data on the backend like this:

  $filename = $_FILES['file']['name'];
  $contacts = $_POST['contact'];
  foreach($contacts as $contact) {
    echo "Name: " + $contact['name'] + "\n";
    echo "E-mail: " + $contact['email'] + "\n";
  }
  $destination = '../assets/img/users/' . $filename;
  move_uploaded_file( $_FILES['file']['tmp_name'] , $destination );
Clone this wiki locally