[Added] uppy - File Uploader
Posted: Fri Jul 22, 2022 7:35 pm
Code: Select all
// Allowed file extensions
$allowed = array('png', 'jpg', 'jpeg', 'bmp', 'pdf', 'xlsx', 'xls', 'csv', 'txt', 'docx', 'pptx');
// Maximum file size
$maxfilesize = 5 * 1024 * 1024; // (5 MB)
$filename = nuSanitizeFilename(basename($_FILES['file']['name']));
$target_dir = $_SERVER['DOCUMENT_ROOT']. '/';
$target_file = $target_dir . $filename;
$error = nuTranslate('Sorry, there was an error uploading your file.');
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
$data = ['error' => $error,
'message' => nuTranslate('Invalid file type')];
$result = json_encode($data);
return;
}
$filesize = $_FILES["file"]["size"];
if ($filesize > $maxfilesize) {
$data = ['error' => $error,
'message' => nuTranslate('File size exceeded')];
$result = json_encode($data);
return;
}
try {
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
$data = ['url' => $target_file,
'file' => $filename,
'message' => 'The file ' . $filename . ' has been uploaded.'];
http_response_code(201);
$result = json_encode($data);
} else {
throw new Exception(nuTranslate('Unable to move the uploaded file to its final location:') . $target_file);
}
} catch (\Throwable $th) {
$data = ['message' => $error,
'error' => $th->getMessage()];
$result = json_encode($data);
}
Code: Select all
<div id="#uppy_div#"></div>
<script>
nuInitUppy();
function nuInitUppy() {
const $objId = $('#' + '#this_object_id#');
const target = '#' + '#uppy_div#';
let uppy = new Uppy.Core();
uppy.use(Uppy.Dashboard, {
inline: true,
bundle: true,
height: $objId.cssNumber('height'),
width: $objId.cssNumber('width'),
target: target,
showProgressDetails: true,
replaceTargetContent: true,
method: 'post'
})
.use(Uppy.XHRUpload, {
endpoint: 'core/nuapi.php'
})
uppy.on('file-added', (file) => {
uppy.setMeta({
procedure: 'NUUPLOADFILE_TEMPLATE',
session_id: window.nuSESSION
})
});
uppy.on('complete', (result) => {
if (window.nuOnFileUploadComplete) {
nuOnFileUploadComplete('FS', $objId.attr('id'), result);
}
})
}
</script>
Code: Select all
let uppy = new Uppy.Core();
Code: Select all
let uppy = nuUppyCreate();