Custom File Upload PHP Script
Custom File Upload PHP Script
HI,
I'm using a custom backend built with MODX. I have everything working nicely except reading back the data of uploads. I don't really understand how this part works.
My server code looks like this:
if ($_POST['action'] === 'upload') { // image uploaded via AJAX
function processName($file){
$path_parts = pathinfo($file);
$filename = $path_parts['filename'];
$ext = $path_parts['extension'];
$newfilename = preg_replace( '/[^a-z0-9]+/', '-', strtolower( $filename ) );
$newfilename = $newfilename .uniqid().'.'.$ext;
return $newfilename;
}
if (is_uploaded_file($_FILES['upload']['tmp_name'])){
$newfilename = processName($_FILES['upload']['name']);
move_uploaded_file($_FILES['upload']['tmp_name'], 'images/debugnfixes/'.$newfilename);
$tableRow = $modx->newObject('system21extras\Model\ExtrasBugsnFixesImages');
$tableRow->set('filename', $newfilename);
$tableRow->save();
$tableData = $tableRow->toArray();
$data = array(
"data" => array(),
"files" => array(
"files" => array(
"1" => array(
"id" => "1",
"filename" => $newfilename,
"web_path" => 'images/debugnfixes/'.$newfilename,
)
)
),
"upload" => array(
"id" => $tableData['id']
)
);
return json_encode($data, JSON_UNESCAPED_SLASHES);
}
}
The upload section of the form looks like this:
{
label: "Screen:",
name: "screen",
type: "upload",
display: function ( id ) {
return '<img src="'+editor.file( 'system21extras_bugsnfixesimages', id ).webPath+'"/>';
},
noImageText: 'No image.'
},
The file is uploaded and the database updated.
I get this console error: Unknown file table name: system21extras_bugsnfixesimages
I don't really understand how the form code above uses the returned data from the backend to show the uploaded file. Also when the table is displayed, how do the upload fields get the image data?
Thanks,
Andrew
Answers
I've worked it out. I thought there was some more AJAX stuff happening and I didn't notice a couple of typos I made.
Backend for upload:
Backend for table view:
JS Editor:
JS Table:
Hi,
Sorry I missed your thread before, but very glad to hear you've got it working now. I hadn't heard of MODX before - it looks really interesting.
Allan