I am trying to remove image in froala text editor, I can upload image, but i can't delete image.
Here is what I am trying to achieve:
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href='https://cdn.jsdelivr.net/npm/froala-editor#latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />
<script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor#latest/js/froala_editor.pkgd.min.js'></script>
</head>
<body>
<div class="sample">
<h2>File upload example.</h2>
<form>
<textarea id="edit" name="content"></textarea>
</form>
</div>
<script>
new FroalaEditor('#edit', {
imageUploadURL: 'upload_image.php',
fileUploadParams: {
id: 'my_editor'
}
})
var editor = new FroalaEditor('#edit');
editor.opts.events['image.removed'] = function (e, editor, $img) {
$.ajax({
// Request method.
method: 'POST',
// Request URL.
url: 'delete_image.php',
// Request params.
data: {
src: $img.attr('src')
}
})
.done (function (data) {
console.log ('Image was deleted');
})
.fail (function (err) {
console.log ('Image delete problem: ' + JSON.stringify(err));
})
}
</script>
</body>
</html>
upload_image.php :
<?php
try {
// File Route.
$fileRoute = "/uploads/";
$fieldname = "file";
// Get filename.
$filename = explode(".", $_FILES[$fieldname]["name"]);
// Validate uploaded files.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
// Get temp file name.
$tmpName = $_FILES[$fieldname]["tmp_name"];
// Get mime type.
$mimeType = finfo_file($finfo, $tmpName);
// Get extension. You must include fileinfo PHP extension.
$extension = end($filename);
// Allowed extensions.
$allowedExts = array("gif", "jpeg", "jpg", "png", "svg", "blob");
// Allowed mime types.
$allowedMimeTypes = array("image/gif", "image/jpeg", "image/pjpeg", "image/x-png", "image/png", "image/svg+xml");
// Validate image.
if (!in_array(strtolower($mimeType), $allowedMimeTypes) || !in_array(strtolower($extension), $allowedExts)) {
throw new \Exception("File does not meet the validation.");
}
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
$fullNamePath = dirname(__FILE__) . $fileRoute . $name;
// Check server protocol and load resources accordingly.
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] != "off") {
$protocol = "https://";
} else {
$protocol = "http://";
}
// Save file in the uploads folder.
move_uploaded_file($tmpName, $fullNamePath);
// Generate response.
$response = new \StdClass;
$response->link = $protocol.$_SERVER["HTTP_HOST"].dirname($_SERVER["PHP_SELF"]).$fileRoute . $name;
// Send response.
echo stripslashes(json_encode($response));
} catch (Exception $e) {
// Send error response.
echo $e->getMessage();
http_response_code(404);
}
?>
delete_image.php :
<?php
try {
$response = FroalaEditor_Image::delete($_POST['src']);
echo stripslashes(json_encode('Success'));
}
catch (Exception $e) {
http_response_code(404);
}
?>
I didn't find any other tutorial in this field and the official site tutorial was not enough.
I tried for a whole day, but it didn't work.
I sincerely appreciate your help.
Related
I'm implementing image upload using CKEditor in laravel but images are uploaded but they're not displayed. I need help, please.
these are my code
public function upload(Request $request){
if($request->hasFile('upload')){
$originalName=$request->file('upload')->getClientOriginalName();
$fileName=pathinfo($originalName,PATHINFO_FILENAME);
$extension=$request->file('upload')->getClientOriginalExtension();
$fileName=$fileName.'_'.time().'.'.$extension;
$request->file('upload')->move(public_path('images'),$fileName);
$CKEditorFuncNum=$request->input('CKEditorFuncNum');
$url=asset('public/images/'.$fileName);
$msg='Image uploaded successfully';
$response="<script >window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum,'$url','$msg')</script>";
#header('content-type:text/html','charset-utf-8');
echo $response;
}
}
and output is this
put these script to your html file
<script src="https://cdn.ckeditor.com/4.14.1/standard/ckeditor.js"></script>
<script>
CKEDITOR.replace( 'summary-ckeditor', {
filebrowserUploadUrl: "{{route('ckeditor.upload', ['_token' => csrf_token() ])}}",
filebrowserUploadMethod: 'form'
});
and put these code in your image controller
if($request->hasFile('upload')) {
$originName = $request->file('upload')->getClientOriginalName();
$fileName = pathinfo($originName, PATHINFO_FILENAME);
$extension = $request->file('upload')->getClientOriginalExtension();
$fileName = $fileName.'_'.time().'.'.$extension;
$request->file('upload')->move(public_path('images'), $fileName);
$CKEditorFuncNum = $request->input('CKEditorFuncNum');
$url = asset('images/'.$fileName);
$msg = 'Image uploaded successfully';
$response = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";
#header('Content-type: text/html; charset=utf-8');
echo $response;
}
I'm not sure how to access the javascript object correctly I think. I'm trying to use ajax to upload a file to php and have the php file handle an unzip to specific directories.
I'm not sure how the unzip would go but I have have the following code so far:
HTML:
<form id="upload_header_modules_form1" enctype="multipart/form-data" method="post" action="" onsubmit="return false">
<label for="themes_edit_file_id1" class="themes_edit_file">Upload .zip file</label>
<input id="themes_edit_file_id1" style="visibility:hidden;" onchange="setfilename1(this.value);" type="file">
<label for="install1" class="normal_button" onclick="uploadZip()">Install</label>
<input id="install1" style="visibility:hidden;" type="submit">
</form>
AJAX:
function uploadZip()
{
formdata = new FormData(document.forms[0]);
if (formdata)
{
$.ajax
(
{
url: "http://localhost/IG_API_2/pages/default_upload/upload_php.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (data)
{
$(".modal").css("opacity", "1");$(".modal").css("visibility", "visible");$(".modal_mid").html("<pre>" + data + "</pre>");
alert(data);
}
}
);
}
}
and PHP (I haven't checked the PHP much so don't pay too much attention to this):
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
/* PHP current path */
$path = '../plugins/'; // absolute path to the directory where zipper.php is in
$filenoext = basename ($filename, '.zip'); // absolute path to the directory where zipper.php is in (lowercase)
$filenoext = basename ($filenoext, '.ZIP'); // absolute path to the directory where zipper.php is in (when uppercase)
$targetdir = $path . $filenoext; // target directory
$targetzip = $path . $filename; // target zip file
/* create directory if not exists', otherwise overwrite */
/* target directory is same as filename without extension */
if (is_dir($targetdir)) rmdir_recursive ( $targetdir);
mkdir($targetdir, 0777);
/* here it is really happening */
if(move_uploaded_file($source, $targetzip)) {
$zip = new ZipArchive();
$x = $zip->open($targetzip); // open the zip file to extract
if ($x === true) {
$zip->extractTo($targetdir); // place in the directory with same name
$zip->close();
unlink($targetzip);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
I'm just wanting to
a) get past the PHP error "Undefined Index zip_file in C:\etc"
b) extract the .ZIP file to location "temp/"
Thanks in advance.
Edit We know that the PHP error is an undefined index because the file type is not loading correctly in the $_FILES["zip_file"]. It's not getting the file because of ajax for some reason. I think it's to do with the formdata = new FormData(document.forms[0]); line.
I am sending formdata from Angular 2 to Laravel API to save the recorded voice from RecordRTC js. Checked the filename, filetype and blob file on console. it is showing. but not able to retrieve on Laravel backend code.
public uploadToServer() {
let blob = this.recordRTC instanceof Blob ? this.recordRTC : this.recordRTC.blob;
let fileType = blob.type.split('/')[0] || 'audio';
let fileName = (Math.random() * 1000).toString().replace('.', '');
if (fileType === 'audio') {
fileName += '.' + (!!navigator.mozGetUserMedia ? 'ogg' : 'wav');
} else {
fileName += '.webm';
}
// create FormData
var formData: FormData = new FormData();
console.log(fileName);
console.log(blob);
console.log(fileType);
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
console.log(formData);
this.recordingService.saveRecording(formData).subscribe(
data => this.saveRecordingSuccess(data),
error => this.saveRecordingFail(error)
);
}
Laravel Code:-
public function saveRecording(Request $request)
{
$fileName = '';
$tempName = '';
$file_idx = '';
if (!empty($_FILES['audio-blob'])) {
$file_idx = 'audio-blob';
$fileName = $_POST['audio-filename'];
$tempName = $_FILES[$file_idx]['tmp_name'];
}
if (empty($fileName) || empty($tempName)) {
if(empty($tempName)) {
echo 'Invalid temp_name: '.$tempName;
return;
}
echo 'Invalid file name: '.$fileName;
return;
}
$filePath = public_path('voiceRecording/' . $fileName);
// make sure that one can upload only allowed audio/video files
$allowed = array(
'webm',
'wav'
);
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
if (!$extension || empty($extension) || !in_array($extension, $allowed)) {
echo 'Invalid file extension: '.$extension;
return;
}
if (!move_uploaded_file($tempName, $filePath)) {
// error code
return;
}
}
In laravel code I have not receiving any files and post data.
You have to put on your form the mime type, like in JQuery Ajax, have the property
mimeType: "multipart/form-data"
I want to use Dropzone.js to store files to the server and also store the file link to the MySQL database. But I can't find a way to get it return the link of the uploaded files.
How can I do with this?
Here's the code:
<section id="home">
<form action="handler.php?user_id=<?php echo $user->data()->id; ?>" class="dropzone" id="my-dropzone">
<div class="fallback">
<input name="file" type="file" multiple id="up" />
</div>
</form>
</section>
<script>
Dropzone.options.myDropzone = {
addRemoveLinks: true,
init: function() {
thisDropzone = this;
$.get('handler.php?action=show', function(data) {
$.each(data, function(key,value){
var mockFile = { name: value.name, size: value.link};
thisDropzone.options.thumbnail.call(thisDropzone, mockFile, "uploads/<?php echo $user->data()->id; ?>/"+value.name);
});
});
thisDropzone.on('removedfile', function(file){
$.get('handler.php?action=remove&name='+file.name+'&user_id=<?php echo $user->data()->id; ?>');
});
}
}
</script>
handler.php:
<?php
define('DS',DIRECTORY_SEPARATOR);
define('DES','uploads');
$action = "upload";
if (isset($_GET['action'])) {
$action = $_GET['action'];
}
//routing for different tasks
switch($action) {
case 'upload':
if (!empty($_FILES)) {
storeFile($_FILES, $_GET['user_id']);
}
break;
case 'remove':
$filename = $_GET['name'];
removeFile($filename, $_GET['user_id']);
break;
case 'show':
showFiles();
break;
}
function storeFile($file, $user_id) {
$tempFile = $file['file']['tmp_name'];
//file extensions allowed
$allowedExt = array('gif', 'jpg');
//file size allowed in kb
$allowedMaxSize = 10240;
//file extension validation
if ( count($allowedExt) >0 ) {
$fileExt = pathinfo($file['file']['name'],PATHINFO_EXTENSION);
if ( !in_array( $fileExt, $allowedExt ) ) {
header("HTTP/1.0 500 Internal Server Error");
echo 'Invalid file extension';
exit();
}
}
//file size validation
if ( (filesize($tempFile)/1024)> $allowedMaxSize ) {
header("HTTP/1.0 500 Internal Server Error");
echo 'File exceeds maximum allowed size';
exit();
}
//move file to server
$targetPath = dirname( __FILE__ ) . DS . DES . DS . $user_id;
if (!is_dir($targetPath)) {
mkdir($targetPath);
}
$targetFile = $targetPath . DS . $file['file']['name'];
if ( !move_uploaded_file($tempFile,$targetFile) ) {
header("HTTP/1.0 500 Internal Server Error Not Found");
echo 'Unknown server error';
exit();
}
}
function showFiles() {
$result = array();
$files = scandir(DES);
if ( false!==$files ) {
foreach ( $files as $file ) {
//ignore current and parent folder indicator
if ( '.'!=$file && '..'!=$file) {
$obj['name'] = $file;
$obj['size'] = filesize(DES.DS.$file);
$result[] = $obj;
}
}
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
}
function removeFile($fileName, $user_id) {
$targetPath = dirname( __FILE__ ) . DS . DES . DS . $user_id . DS;
$targetFile = $targetPath . $fileName;
//remove only when file exists
if (file_exists($targetFile)) {
unlink($targetFile);
}
}
?>
Not sure if you have resolved your issue, but I use this example and all works well
Dropzonejs Example
index.php
<html>
<head>
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
</head>
<body>
<form action="upload.php" class="dropzone">
</form>
<script src="js/dropzone.min.js"></script>
</body>
</html>
upload.php
<?php
//require 'yourconnectionfile.php';
//I'm using mysql_ as an example, it should be PDO
$ds = DIRECTORY_SEPARATOR;
$foldername = "./uploads";
if (!empty($_FILES)) {
$fileupload = basename( $_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
$targetFile = $targetPath. $fileupload;
move_uploaded_file($tempFile,$targetFile);
//Your Upload SQL goes here
//$uploadsql = "INSERT INTO uploads (Filename, description, Type, Size)
// VALUES ('$fileupload', 'test uploads', '$fileType', '$fileSize')";
//mysql_query($uploadsql);
}
?>
Use the example above to get the css & the js code along with a couple of images.
I'm trying to upload files using php and I am copying and renaming files from other instances that are actually working (uploading pics). But for some reason the form is not passing (POST) any file that is NOT an image :-/
So, in resume, I am getting this (Google) 'request payload' for an image file:
------WebKitFormBoundaryrHOYostaC2KnUDlD
Content-Disposition: form-data; name="uploaded_file[]"; filename="image.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryrHOYostaC2KnUDlD--
But this for txt or pdf files:
------WebKitFormBoundaryc1RJOtSOpYKAZiBz--
Here is the form and script (functions are to avoid the user to click 'Submit', those work good):
echo '
<script language="JavaScript" type="text/javascript">
function HandleBrowseClick()
{
var fileinput = document.getElementById("uploaded_file");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("uploaded_file");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>';
echo '
<form enctype="multipart/form-data" target="_blank" name="send_file" id="send_file" method="post" action="file_upload.php">
<input type="file" class="hide button" id="uploaded_file" name="uploaded_file" onChange="Handlechange();"/>
<button type="submit" id="btn">Upload!</button>
</form>';
echo '
<div onclick="HandleBrowseClick();" id="fakeBrowse" >Load a file</div>
<input type="text" id="filename" size="50" readonly="true" />
';
So, since it's not passing anything, in my file_upload.php I get the "ERROR: Please browse for a file before clicking the upload button." or "Invalid argument supplied for foreach()" (if I expect an array) error.
I tried using application/x-www-form-urlencoded allowing the same result. Now for those who get mad if there is no question marks: Why the form works fine with images but not so with other kind of files? What am I dong wrong?
Here is the first few lines of file_upload.php (I don't think it's necessary but you never know):
$target = "../files/temp/";
foreach ($_FILES["uploaded_file"]["error"] as $key => $error) {
if ($error != UPLOAD_ERR_OK) { echo "error"; die;}
$fileName = $target . $_FILES["uploaded_file"]["name"][$key]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"][$key]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"][$key]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"][$key]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"][$key]; // 0 for false... and 1 for true last $key!!!
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename
$fileName = strtolower($fileName);
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occurred while processing the file. Try again.";
exit();
}
Finally, some more js:
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
input.addEventListener("change", function (evt) {
document.getElementById("response").innerHTML = "Loading . . ."
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if (formdata) {
formdata.append("uploaded_file[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false
}).done(function (res) {
document.getElementById("response").innerHTML = res;
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
});
}
}, false);
where changing contentType doesn't make any diference
THANKS!!!
You have to define the MIME types for your files. For example
.pdf application/pdf
.doc application/msword
Okay, my bad. The js file has an image filter. It started working right away after I removed it.