Skip to content

Instantly share code, notes, and snippets.

@ipanardian
Last active February 16, 2018 12:16
Show Gist options
  • Save ipanardian/d938004a058a89bbce8e12fb2e9ee714 to your computer and use it in GitHub Desktop.
Save ipanardian/d938004a058a89bbce8e12fb2e9ee714 to your computer and use it in GitHub Desktop.
Async Upload File
<?php
/**
* PHP Example for jQuery Image Reader
*/
header('Content-type: application/json; charset=utf-8');
try {
// Check MIME Type
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['photos']['tmp_name'][0]),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
#save image
if (!move_uploaded_file(
$_FILES['photos']['tmp_name'][0],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['photos']['tmp_name'][0]),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
die(json_encode(['message' => 'Image is uploaded successfully.']));
}
catch (RuntimeException $e) {
die(json_encode(['message' => $e->getMessage()]));
}
$.uploadFile = function() {
var files = $('#upload-file').prop('files');
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image.*')) {
continue;
}
formData.append('photos[]', file, file.name);
}
$.ajax({
type: "POST",
url: 'save.php',
data: formData,
processData: false,
contentType: false,
}).done(function(data){
alert(data.message)
}).fail(function() {
alert('An error occurred.')
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment