Issues in image uploading using vue-wysiwyg - javascript

I am using vue-wysiwyg editor in my laravel-vue application. In this editor there is an option to upload images and through incomplete documentation of this package I am able to upload the image and get public url of the uploaded file. But this package works sometimes and does not work at all sometimes.
Here is how I am using this package
main.js
import wysiwyg from "vue-wysiwyg";
Vue.use(wysiwyg, {
forcePlainTextOnPaste: true,
image: {
uploadURL: "/api/save-support-files",
dropzoneOptions: {}
},
});
/api/save-support-files
public function uploadUserFile(Request $request)
{
$uploadedFile = $request->file('file');
if (false == $uploadedFile) {
return response()->api(false, 'Kindly upload a file');
}
$allowed_file_extentions = [
'jpeg',
'png',
'jpg',
'gif',
'svg'
];
if (false == in_array($uploadedFile->getClientOriginalExtension(), $allowed_file_extentions)) {
return response()->api(false,'Allowed file types are jpeg, png, jpg, gif, svg',null);
}
$file_url = Storage::disk('public')->putFileAs('/support-files',$uploadedFile,generateRandomString('5').'.'.$uploadedFile->getClientOriginalExtension());
// return response()->api(true,'File uploaded successfully',config('app.url').'/storage/'.$file_url);
return config('app.url').'/storage/'.$file_url;
}
Issues I am facing right now:
As soon as I select image from file browser, image is uploaded through api successfully but it is not showing in editor.
Unable to select already uploaded image, I have to refresh the page and then again select file to upload it again.
Is anyone having solution to this problem ? Kindly help me out.

my upload store function look like this:
public function store(Request $request)
{
$request->validate(['file' => 'required']);
$file = $request->file('file');
if ($file->isValid()) {
$path = $file->storePublicly(now()->format('Y' . DIRECTORY_SEPARATOR . 'm' . DIRECTORY_SEPARATOR . 'd'));
return response(Storage::disk('public')->url($path), Response::HTTP_CREATED)->withHeaders(
[
'content-type' => 'text/html'
]
);
}
abort(Response::HTTP_BAD_REQUEST);
}
make sure you have set APP_URL in .env to full url (http://my-site.com)
make sure you run php artisan storage:link

Related

how to create window.location response in ajax

For creating a .zip file for checked items with selectbox, i need a response back from the php that leads to the path the .zip file is stored.
This is my ajax call:
// AJAX for Checkbox download
$(document).on('click' , '.cb_down' , function() {
var checkboxes_down = [];
$('.rafcheckbox').each(function() {
if(this.checked) {
checkboxes_down.push($(this).val());
}
});
checkboxes_down = checkboxes_down.toString();
$.ajax({
url:"",
method:"POST",
data:{ checkboxes_down:checkboxes_down },
success:function(response){
window.location = response; // this should lead me to the zip file
}
//.........
My php:
// Multiple download (checkboxes)
if(isset($_POST["checkboxes_down"])) {
// create a tmp folder for the zip file
$tmpfolder = $MainFolderName.'/tmpzip';
if (!is_dir($tmpfolder)) {
mkdir($tmpfolder, 0755, true);
}
$checkboxfiles = explode("," , $_POST["checkboxes_down"]);
$filename = "archive.zip";
$filepath = $tmpfolder."/";
foreach($checkboxfiles as $checkboxfile) {
Zip($checkboxfile, $tmpfolder."/archive.zip"); // Zip is a function that creates the .zip file
}
// header come here
echo $filepath . $filename; // the path to the .zip file
exit;
The .zip file is successful created. I checked it.
The problem is: i do not get the response back from the php script.
So i can not download the .zip file.
What i am doing wrong?
! I changed the echo to 'zip file is created' but even that echo i do not receive as response back

angularjs can't show file from api

I have an app where frontend is developed in angularjs and backend with symfony.
I need to have a route like: http://example.com/api/invoices/file?file=foo
So I have this inside my FileController:
/**
* Matches /invoices/file/{filename} exactly
*
* #Route("/invoices/file/{filename}", name="get_invoice_file")
*/
public function getInvoiceFileAction(string $filename, Request $request)
{
$path = $this->get('kernel')->getRootDir() . '/../web/uploads/invoices/' . $filename;
if (!file_exists($path)) {
return new Response('file not found', 404);
}
$file = file_get_contents($path);
$headers = [
'Content-Type' => 'application/pdf',
'Conteng-Length' => filesize($path)
];
return new Response($file, 200, $headers);
}
Inside my angularjs app I have this to get the response inside my frontend controller:
vm.getInvoices = function() {
vm.loading = true;
apiResolver.resolve('invoices.documents.file#get', { "file": vm.searchFile }).then(function(response) {
vm.loading = false;
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
vm.file = $sce.trustAsResourceUrl(fileURL);
});
};
Into my html I have this:
<embed ng-src="{{vm.file}}" style="width:200px;height:200px;"></embed>
When I render the page I see a 200response so the file exist but into the html I have an empty space instead of pdf file.
Inside embed tag there is this:
<embed style="width:200px;height:200px;" ng-src="blob:http://localhost:3000/d32d87d1-6582-42e3-85ae-dc174ca5a473" src="blob:http://localhost:3000/d32d87d1-6582-42e3-85ae-dc174ca5a473">
If I copy url inside a browser returns me that can't load file.
Backend and frontend are in different folder and the pdf CAN'T be viewed by a public link infact these pages are protected with jwt system.
How can I show inside my page the pdf?
What I'm doing wrong?
Make sure that JWT Authorization Token is passed in the request . If not , pass it in the Blob object.
If token is passed try replacing embed to object as mentioned below :
<object data="{{vm.file}}" style="width:200px;height:200px;" type="application/pdf"></object>

image wont render, path is base on the storage path

I have this function on my controller
public function get_images(Request $request){
$images = inventory_images::where('item_id',$request->id)->get();
$path = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
return response()->json([ 'success' => true, 'images' => $images, 'id' => $request->id, 'path' => $path ]);
}
so the '$path' contains the storage path, my images stored on the 'storage' folder and the '$images' contains the file name and then in my front end side (rendering the image)
$.each(e.images,function(index,value){
$("#notification_dialog #gallery-items-container").append(' <figure> <img src="'+e.path+value.image_name+'"> </figure>');
});
in the image 'src' I have this path
C:\wamp\www\Clinic and Inventory
System\storage\app\public\items_gallery\10014589_974440645904700_5867266076580720168_n.jpg
In the console, I have this error
:1 Not allowed to load local resource:
file:///C:/wamp/www/Clinic%20and%20Inventory%20System/storage/app/public/items_gallery/10014589_974440645904700_5867266076580720168_n.jpg
The image did not render and If I paste the path unto the browser, I can see the image so it means that the path was correct and just the image is not rendering, any ideas, help please?
Put a data attribute on the tag holding the image:
data-image_path="{{ asset('uploads/*name of model this is being associated with/original/') }}"
Where asset points to your project's public directory.
Then retrieve the image name from the controller and append it to that path.
I have found a solution somewhere,
Route::get('/images/{image}', function($image = null)
{
$path = storage_path().'/app/public/items_gallery/' . $image;
if (file_exists($path)) {
return Response::download($path);
}
});
and its okay now.

Froala - image upload JSON response

I am using Froala editor for my website. This editor have built in image upload function - image upload is working fine, but I am having trouble with response.
This is from the documentation:
The server processes the HTTP request.
The server has to process the upload request, save the image and return a hashmap containing a link to the uploaded image. The returned hashmap needs to look like: { link: 'path_to_uploaded_file/file.png' }
This is my function for returning link:
public function froala_upload()
{
header('Content-type: application/json');
$folder = 'public/img/media';
$slika = $this->site->single_upload($folder, 'jpg|jpeg|png|bmp|JPG|JPEG|PNG|BMP');
$link = array("link" => $slika);
echo json_encode($link);
}
This is JS code:
$('textarea').editable({
inlineMode: false,
imageUploadParam: "userfile",
imageUploadURL: "<?php echo base_url() ?>admin/froala_upload",
// Set the image error callback.
imageErrorCallback: function (data) {
// Bad link.
if (data.errorCode == 1) {
console.log(data);
}
// No link in upload response.
else if (data.errorCode == 2) {
console.log(data);
}
// Error during file upload.
else if (data.errorCode == 3) {
console.log(data);
}
}
});
When I upload image I get following error:
Object { errorCode=1, errorStatus="Bad link."}
And this is response that I get:
{"link":"7d59d61.jpg"}
What seem to be a problem?
Froala image upload documentation
You must return the absolute image path :
$link = array("link" => '/img/media/'.$slika);
Because Froala looks for it to http://example.com/7d59d61.jpg
The problem is that the image cannot be loaded from the returned link. You'd have to make sure that the image can be accessed from it. Froala Editor uses the link you return for src attribute from img tag. I think you'd have to do something like:
$link = array("link" => $slika . 'public/img/media');

Uploadify - onComplete || onAllComplete not work

I know there are already some threads with this question, but none was helpful to me.
I have an image manager and I would like to reload the page with "onComplete" event, but it not work for me.
you can see an example: http://graficnova.com/uploadifytest/imgLoader.php
Everything works successful!!, but u need press f5 key for refresh it :(.
Thx and sorry for my english!
code:
head:
<script type="text/javascript">
$(function() {
$("#fileInput").uploadify({
width : 100,
swf : 'swf/uploadify.swf',
uploader : 'php/uploadify.php',
queueID : 'imgloadList',
oncomplete : function() {
alert('hello world?'); //<- THIS NOT WORK
}
});
});
</script>
php: uploadify.php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
//$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetPath = 'xxxxx/xxxx/xxxx/xxxx';
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo '1'; //<- return response
} else {
echo 'Invalid file type.'; //<- return response
}
}
Based on the Uploadify docs, there isn't an onComplete event, but there is an 'onUploadComplete' event:
Triggered once for each file when uploading is completed whether it was successful or returned an error. If you want to know if the upload was successful or not, it’s better to use the onUploadSuccess event or onUploadError event.
Might want to give that a try. Or check out onQueueComplete.

Categories