JQuery Fine Uploader S3 uploadsuccess params on file size - laravel

Need a little help on pass the upload file size variable to the endpoint (the php controller). I tried multiple ways, but seems the method is not working.
First of all, I am not be able to get upload file 'id' which is necessary for getSize function.
Secondly, system through errors when I put getSize function in the parames: object.
part of my code below:
var loader=$('#fine-uploader-s3').fineUploaderS3({
... ...
//deleted not relevant code above
uploadSuccess: {
endpoint: "/s3/uploadSuccessful",
customHeaders:
{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
params: {
user_id:'{{Auth::user()->id}}', // there are params I want to
lot_id: '{{$lot->id}}', //pass to the controller
//no issue. the php controller
//got them. this code is part of
.. ... //Laravel blade.
size: function (){
return this.uploaderMethods.getSize('0');
//hard code file id 0 for test. not working.
Or I have tried: size: function (){
return this.getSize('0');
Or size: $('#fine-uploader-s3').fineUploaderS3('getSize', '0'),
None of them works. Thanks for any help here.

Found an answer in the docs using setUploadSuccessParams. Add a callback block such as below:
callbacks: {
onSubmit: function (id, fileName) {
var size = this.getSize(id);
var newParams = {"size": size};
loader.setUploadSuccessParams(newParams, id)
}
},

Related

Pass DataTable reference to the callback function on load

My current code is:
var CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: ajaxurl + '?action=pos&post_action=get_commissions'
},
'initComplete': function (settings, json){
//possible to access 'this'
this.api().columns(1);
}
});
I improved the code above as below with help :
var CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: ajaxurl + '?action=pos&post_action=get_commissions'
},
'initComplete': function(settings, json){
callbackFunction(settings);
}
});
function callbackFunction(settings){
var api = new $.fn.dataTable.Api( settings );
// api is accessible here.
}
Update :
Now I can access api from callback function. But I want use same callback with load() as below code.
CommissionLogs.ajax.url( newAjaxURL ).load( callbackFunction(), true);
But settings param is not accessible in load function.
I can clear and destroy datatable and re initialize always. But what will be the right way.
I think you need settings:
https://datatables.net/reference/type/DataTables.Settings
$('#example').dataTable( {
"initComplete": function(settings, json) {
myFunction(settings);
}
});
function myFunction(settings){
var api = new $.fn.dataTable.Api( settings );
// Output the data for the visible rows to the browser's console
// You might do something more useful with it!
console.log( api.rows( {page:'current'} ).data() );
}
Other option is re-use your var CommissionLogs variable throughout the code without using this, I recommend strongly this last option.
The dataTable.ajax.url().load() has not access to settings.
So can not call a callback function with settings.
But possible to use callback function without settings.
So here is an alternative way to use settings.
CommissionLogs.clear();// clear the table
CommissionLogs.destroy();// destroy the table
CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: newAjaxUrl
},
'initComplete': function (settings, json){
callbackDatatableFunciton(settings);
}
});

Get image from blob Laravel vue

First of all, this is the start of where I am at as a similar post
Store blob as a file in S3 with Laravel
I am sending a photo from VueJS to Laravel. It is coming as multipart/form-data.
Vue Code:
export default {
emits: ['onClose'],
props: ['isOpen'],
data: function() {
return {
serverOptions: {
process: (fieldName, file, metadata, load, error) => {
const formData = new FormData();
formData.append(fieldName, file, file.name);
axios({
method: "POST",
url: '/chat/room/upload',
data: formData,
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(() => {
load();
})
.catch(() => {
error();
});
}
},
files: [],
};
},
methods: {
handleFilePondInit: function () {
console.log('FilePond has initialized');
// example of instance method call on pond reference
this.$refs.pond.getFiles();
console.log(this.$refs.pond.getFiles());
},
},
Laravel Controller:
public function uploadImage(Request $request)
{
// This is what this is SUPPOSED to do. Grab the file from the frontend
// Bring it here. Store it in S3, return the path with the CDN URL
// Then store that URL into the DB as a message. Once that is done, then
// Broadcast the message to said room.
if ($request->has('upload')) {
$files = $request->get('photo');
$urls = [];
foreach ($files as $file) {
$filename = 'files/' . $file['name'];
// Upload File to s3
Storage::disk('digitalocean')->put($filename, $file['blob']);
Storage::disk('digitalocean')->setVisibility($filename, 'public');
$url = Storage::disk('digitalocean')->url($filename);
$urls[] = $url;
}
return response()->json(['urls' => $urls]);
}
// broadcast(new NewChatMessage($newMessage))->toOthers();
// return $newMessage;
}
First: I want to state that if there is something wrong with the current code, just know its because ive been playing around with this for 3 hours now and been trying anything. I am sure at one point I had it close but somehow screwed it up along the way so I am more looking for fresh eyes to show me my error.
That being said, the other part to take into account is in DevTools under Network I can clearly see the blob and can load it up, I can also see the "upload" item and under there the form data which shows the following
------WebKitFormBoundary7qD7xdmiQO9U1Ko0
Content-Disposition: form-data; name="photo"; filename="6A8B48B4-F546-438E-852E-C24340525C20_1_201_a.jpeg"
Content-Type: image/jpeg
------WebKitFormBoundary7qD7xdmiQO9U1Ko0--
it clearly also shows photo: (binary) so I am completely confused as to what I am doing wrong. The ULTIMATE goal here is to get the image, store it as public in S3/DigitalOcean then grab the public URL to the file and store in the DB.
Any help would be GREATLY appreciated!

Basic implementation of ajax in magento

I am a newbie in magento and trying to implement ajax,but can't find a proper tutorial to follow. Could anyone provide me some reference or guide me to where i would be able to find it?
Don't know a tutotial but I can explain you bit what I implemented in a project a month back.
I created a controller on which we can fire an AJAX request on a specific action. In this case the getoptionsAction in the IndexController of our custom Offerte module.
The getoptionsAction in my controller takes a product_id and loads the options for the product. It builds the HTML and echo's this on function end.
In phtml file I have following code to invoke the AJAX request and update html-object in frontend:
function get_options(prod_id){
var product_options = $('product_options');
var prod_id = $('product').getValue();
new Ajax.Updater('product_options',
'<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); ?>offerte/index/getoptions',
{ method: 'get',parameters: {prod_id: prod_id, type: 'get_regular_options' } ,
onCreate: function(){
$('loading-img-options').show();
},
onComplete: function (t) {
$('loading-img-options').hide();
$('product_options').show();
}
});
}
the above function uses Ajax.Updater. You can also use Ajax.Request to get the result to juggle with.
function stripslashes(str) {
return str.replace(/\\'/g,'\'').replace(/\"/g,'"').replace(/\\\\/g,'\\').replace(/\\0/g,'\0');
}
function get_products(){
product = $('product');
cat_id = $('category').value;
new Ajax.Request('<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); ?>offerte/index/getproducts',
{method: 'get', parameters: {cat_id: cat_id, mode: 'offerte'},
onCreate: function(){
$('product-loading').show();
$('product_options').hide();
},
onSuccess: function(t) {
resp = jQuery.parseJSON(t.responseText);
$('prod-container').innerHTML = resp.options ? stripslashes(resp.options) : '<?php echo $this->__('No options found') ?>';
$('product-loading').hide();
}
});
}
(please note I use JQuery to parseJSON. You can also use String.evalJSON, but I was lazy here :-)
Using Ajax.Request you need to return the result from the controller as JSON. I used the code below in my controller to return JSON to our phtml to use in the onSuccess Callback function above:
$this->getResponse()->setBody(Zend_Json::encode($result));
Hope this is of any help

Valums Ajax Upload with Codeigniter: Get Parameters!

How do I use paramaters with Valums Uploader and Codeigniter?
With Valums the parameters are set like so:
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/server-side.upload',
// additional data to send, name-value pairs
params: {
param1: 'value1',
param2: 'value2'
}
});
or using
uploader.setParams({
anotherParam: 'value'
});
if you want it to be aware of the state of your app/
subD="/Pic"
function selectGaleryName()
{
subD=subD+"/3"
alert(subD) // /Pic/3
}
var uploader = new qq.FileUploader({
element: document.getElementById('UploadFile'),
action: 'http://localhost/Farainform/manager/upload.php'
// additional data to send, name-value pairs
onComplete: function(id, fileName, responseJSON){
selectGaleryName();
uploader.setParams({
subDirectory : subD
});
},
});
if you want to set an id and a description for an image you can set these in javascript and then send these. So something like (im using jQuery here):
var description = $('#input_description').val(); //This can be an input
var id = $('#input_description').att('id');
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/server-side.upload',
// additional data to send, name-value pairs
params: {
description: description,
id: id
}
});
Note I havent tested this code and its for demonstration purposes.
$_GET was always destroyed in the 1.7.3 branch but upgrade to the new CodeIgniter Reactor 2.0 and you'll find that GET strings work out of the box.
When upgraded, use this syntax:
$this->input->get('value1');
I don't know why it is not documented on Valums page, but apparently parameters should be sent not like this
params: {
param1: 'value1',
param2: 'value2'}
But like this
data: {param1: 'value1',
param2: 'value2'}
On server side you could get them with $_REQUEST['param1'];
You have to use PHP's input stream in order to obtain the data.
$fp = fopen('php://input', 'r');
Then read the data as you normally would with a regular file using fread(). Refer to valum's server side code located in server/php.php within the download.
Two related issues that I ran into that might help someone out:
1) var uploader causes issues - try using something like ajaxuploader instead
2) the documented setParams is incorrect for the latest release - it should be setData
The end result should be something like this:
var ajaxuploader = new AjaxUpload(button, {
action: 'your-server-script.php',
name: 'myfile',
onSubmit : function(file, ext){
ajaxuploader.setData({
somevar : 'somevalue',
anothervar : 'anothervalue'
});
)};

Ajax Upload using valums ajax upload plugin inside a form

i just came across this ajax upload plugin and i wish to use it inside a form as shown in the demo page example 3. For some reason i am not able to make it work. I am not sure what parameters come into the function. For example here is my sample code.
$(document).ready(function(){
var upload = new AjaxUpload('property_i',
{
action: 'submitproperty.php',
autoSubmit: false,
onSubmit : function(file , extension){
return false;
}
});
var upload_data = upload.setData({
'propertytype':'propertytype'
});
});
Now the ID used in the AjaxUpload function should be ID of the or of the Entire form. Also how do i use setData method. Any suggestions or links will be very helpful. Thanks
I got it to work with the following code:
new AjaxUpload('#uploader_button', {
action: 'filename.ashx',
autoSubmit: true,
onSubmit: function(file, ext) {
// --- stuff here
// --- add postdata parameters
this.setData({ id: 1, title: docTitle.val() });
},
onComplete: function(file, response) {
// --- stuff here too
}
});
it doesn't utilize the var but instead adds the custom data params in the onSubmit block. The only other difference is that I haven't wrapped the parameter key in quotes as it seems to serialize correctly. And I'm not using autoSubmit: false , but instead it's true...
The only way I could get this to work with autoSubmit: false is to add this outside any function:
var uploader;
var uploadFile;
then in the AjaxUpload(...
onChange: function(file, response){
uploader = this;
uploadFile = file;
},
then in the function to do the upload:
uploader.setData({session: session});
uploader.submit();
Hope this helps
I'm using uploadify and very useful.
http://www.uploadify.com/

Resources