Cloud Convert job error "started too many jobs at once" - javascript

I'm sending files to a php script from an html form. In the php script, I'm getting the temp file location and trying to convert it from a jpg to png. I'm getting this error from the server when trying to convert the file:
CloudConvert\Exceptions\HttpClientException: You have started too many
jobs at once in
C:\xampp\htdocs\photocloud\vendor\cloudconvert\cloudconvert-php\src\Exceptions\HttpClientException
upload.php:
require 'vendor/autoload.php';
use \CloudConvert\CloudConvert;
use \CloudConvert\Models\Job;
use \CloudConvert\Models\ImportUploadTask;
use \CloudConvert\Models\Task;
$obj_temp = $_FILES['file']['tmp_name'];
$obj_name = $_FILES['file']['name'];
$obj_errors = $_FILES['file']['error'];
$obj_checksum = md5_file($obj_temp, false);
$obj_size = filesize($obj_temp);
$obj_extention = strtolower(pathinfo($obj_name, PATHINFO_EXTENSION));
$cloudconvert = new CloudConvert([
'api_key' => 'my_key_here',
'sandbox' => false
]);
$obj_key = $obj_checksum.'.'.$obj_extention;
$job = (new Job())
->addTask(new Task('import/upload','upload-my-file'))
->addTask(
(new Task('convert', 'convert-my-file'))
->set('input', 'upload-my-file')
->set('output_format', 'png')
)
->addTask(
(new Task('export/url', 'export-my-file'))
->set('input', 'convert-my-file')
);
$cloudconvert->jobs()->create($job);
$url_task = $job->getTasks()->whereName('export-my-file')[0];
$cloudconvert->tasks()->upload($url_task, fopen($obj_temp, 'r'), 'test.png');
$cloudconvert->jobs()->wait($job);
foreach ($job->getExportUrls() as $file) {
echo $file->url;
}
upload.js
var fileInput = document.querySelector('.upload');
$.each(fileInput.files, function(index, val) {
formData = new FormData();
formData.append('file', fileInput.files[index]);
$.ajax({
type: 'POST',
url: 'upload.php',
processData: false,
contentType: false,
data: formData,
success: function(response) {
console.log(response);
}
});
});

Related

Unable to download file in laravel ajax on button click

When I am trying to use the download button to download file in laravel ajax, it is not working properly and I am not able to download file.
Below is my code:
<button type="button" request_id="'.$data->id.'" class="btn btn-success download_request_btn" > Download </button>';
Controller:
public function downloadReport(Request $request)
{
$request_id = $request->request_id;
$downloadReport = Upload::where('id', $request_id)->first();
$upload_report = $downloadReport->upload_report;
$headers = array(
'Content-Type: application/pdf',
'Content-Type: application/docx',
);
$url= url('storage/documents/request/'. $upload_report);
return response()->download($url);
}
Ajax:
$(document).on('click', '.download_request_btn', function(){
var request_id = $(this).attr('request_id');
console.log(request_id);
var formData = new FormData();
formData.append('request_id',request_id);
jQuery.ajax({
type: "post",
url: site_url+"/DownloadAjax",
data: formData,
contentType:false,
processData:false,
success: function (res) {
}
});
});
Just to pseudo-code it up with trusting your data is coming back as desired I think you need to trigger the download in your success callback with a variation of the following (may need to adjust to your need):
$(document).on('click', '.download_request_btn', function(){
var request_id = $(this).attr('request_id');
console.log(request_id);
var formData = new FormData();
formData.append('request_id',request_id);
jQuery.ajax({
type: "post",
url: site_url+"/DownloadAjax",
data: formData,
contentType:false,
processData:false,
success: function (res) {
const data = res;
const link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', 'yourfilename.extensionType'); // Need to modify filename ...
link.click();
}
});
});
you can pass header to force file type and download
$file_path = storage_path('documents/request/'. $upload_report);
$headers = array('Content-Type'=> 'application/pdf');
return \Response::download($file_path, 'file.pdf', $headers);
here you need to add header based on your file type
ref link https://laravel.com/docs/8.x/responses#file-downloads
if(!empty($fileName) && file_exists(($exportDir.'/'.$fileName))) {
$data = route('yourdownloadCSV',['nameFile' => $fileName]);
}
return response()->json([
'status' => 1,
'data' => $data,
'message'=> trans('messages.item_upload_shop_ok'),
]);
public function yourdownloadCSV($nameFile) {
ini_set('memory_limit', '9072M');
ini_set('MAX_EXECUTION_TIME', '-1');
set_time_limit(10*60);
$fullFolderZipFile = public_path().'/export/'.date('ym');
$filePath = $fullFolderZipFile.'/'.$nameFile;
$nameDownload = "test";
if(file_exists($filePath)) {
$byteS = filesize($filePath);
$mb = number_format($byteS / 1048576, 2) ;
if($mb>10){
$filePathZip= ZipUtil::generateZipFromFile($filePath,$fullFolderZipFile,$nameFile);
$nameDownload .=".zip";
}else{
$filePathZip = $filePath;
$nameDownload .=".".pathinfo($nameFile, PATHINFO_EXTENSION);
}
$mimeType = File::mimeType($filePathZip);
return response()->download($filePathZip,$nameDownload,[
'Content-Type' => $mimeType,
'Content-Encoding' => 'Shift-JIS'
])->deleteFileAfterSend(true);
}
return '';
}

Summernote upload not working

My onImageUpload in summer note jquery plugin is not working.
for upload image in some folder different place then summernote default location
how can i handle this ?!
index.php
<textarea id="summernote" name="contents"></textarea>
<script>
$('#summernote').summernote({
tabsize: 2,
height: 200,
focus: true,
callbacks: {
onChange: function(contents, $editable) {
console.log('onChange:', contents, $editable);
}
}
});
$('#summernote').on('summernote.image.upload', function(we, contents, $editable) {
data = new FormData ();
data.append("file",file);
$.ajax({
url: "summernote_upload.php",
type: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
});
$summernote.summernote('insertNode', imgNode);
});
</script>
summernote_upload.php
require_once ('./../../lib/curl_setup.php'); // curl json&token
$data_array = array(
"request" => array(
"image" => "this upload file/base64"
),
);
$make_call = callAPI('POST', '/api/v2/admin/products/images', json_encode($data_array));
$response = json_decode($make_call, true);
//$errors = $response['response']['errors'];
//$data = $response['response']['data'][0];
print_r($response);exit;
However, summernote_upload.php works well.
The response is:
{
"image": {
"shop_no": 1,
"path": "/web/upload/NNEditor/20180408/b69c819e36b4abc3f393b731829ab747.gif"
}
}
I need to solve the index.php.
first you must catch the upload image event
and dont allow to summernote add it automatically
callbacks: {
onImageUpload: function(files, editor, $editable) {
console.log('onImageUpload');
sendFile(files[0],editor,$editable);
}},
then you must handle image upload with json yourself.
there is a function for this:
function sendFile(file,editor,welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
url: "uploader.php",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
// alert(data);
$('#summernote10').summernote("insertImage", data, 'filename');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus+" "+errorThrown);
}
});
}
and in server side you can save the file
$allowed = array('png', 'jpg', 'gif','jpeg');
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
$newFileAddress = '../files/-'.rand(1000).'.'.$extension;
if(move_uploaded_file($_FILES['file']['tmp_name'],$newFileAddress)){
echo $newFileAddress;
exit;
}
}
by return the file path on server you can insert it on summer note easily

Uploading files with Dropzone JS into child folder

I have a form in which I have a field for name and dropzone. So if I go with simple one like to upload files in main upload folder then it is working but I want to upload files in child folder like I am getting folder name through <input type="text" name="name" /> and on upload file should go to new generated folder.
HTML:
<input type="text" name="name" class="form-control fl_name" />
<div class="dropzone"></div>
JS:
// CREATE FOLDER FOR FILE UPLOADS
$('.name-alert').hide();
$('.fl_name').on('change', function() {
var fl_name = 'name='+ $(this).val();
var fl_url = $(this).closest('form').attr('action');
$.ajax({
type: 'POST',
url: fl_url,
data: fl_name,
cache: false,
success: function(result){
if (result == '0') {
$('.name-alert').slideDown();
setTimeout(function() {
$('.name-alert').slideUp();
}, 2000);
}
}
});
});
// CREATE DROPZONE ENVIORMENT
var myDropzone = new Dropzone('div.dropzone', {
url: "http://localhost/build/assets/php/customer-query.php",
addRemoveLinks: true,
init: function() {
this.on('success', function( file, resp ){
var fl_name = 'name='+ $('.fl_name').val();
var fl_url = 'http://localhost/build/assets/php/customer-query.php';
$.ajax({
type: 'POST',
url: fl_url,
data: fl_name,
cache: false,
success: function(result){
console.log(result);
}
});
});
},
});
PHP:
// Create Folder On Input Field Change
$fname = $_POST['name'];
if (!file_exists('../uploads/'.$fname.'/')) {
mkdir('../uploads/'.$fname.'/', 0777, true);
} else {
echo '0';
}
// Upload Files
$fl_name = $_POST['name'];
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '../uploads/'.$fl_name.'/';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) .$ds. $storeFolder .$ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
in my code files are still uploading in main folder instead of new folders.
Thanks
Your "data" in the ajax call doesn't look like a json object. Try changing it to:
$.ajax({
type: 'POST',
url: fl_url,
data: {'name':fl_name},
dataType: "json",
cache: false,
success: function(result){
console.log(result);
}
});
See Passing data with jquery ajax if you need a further example on passing data with json via ajax
You may also be missing the following in your php file to read the json input:
$inputJSON = file_get_contents("php://input");
$result = json_decode($inputJSON,TRUE);
in which case you need to change
$fname = $_POST['name'];
to
$fname = $result['name'];

In Safari $_FILES doesn't work

I need to pass files and other data to ajax.
My code:
var doc = new jsPDF('p', 'pt', 'a4'); // basic create pdf
var pdf = doc.output('blob');
var data = "";
if (flagSend == 1) {
data = new FormData($("#sendInvoiceForm")[0]);
data.append('flagSend', 1);
var send_invoice_subject = $("#send_invoice_subject").val();
} else {
data = new FormData();
data.append('flagSend', 0);
}
data.append('data', pdf);
data.append('invoice_number', invoice_number);
$.ajax({
type: 'POST',
data: data,
processData: false,
contentType: false,
url: sJSUrlSavePdfInvoiceToServer,
dataType: 'json',
success: function (data) {
}
});
In my 'data' I pass a pdf file, and get it in php with $_FILES['data'].
It works well in Chrome,Firefox. But in Safari there is no $_FILES['data'], there is $_REQUEST['data'] - [object Blob]
So I can't upload files in Safari:
if (move_uploaded_file($_FILES["data"]["tmp_name"], $target_file)) {
}
because there is no $_FILES['data'] field.
How can I solve this problem?
Thanks.
Anybody know reason?

AJAX Post to .PHP to JSON Data-set || PHP File

Afternoon guys/gals,
I'm relatively new to using AJAX to POST information to a JSON file and I am not sure what the .php file should look like to process it. I have very little experience with .php. Am I on the right track? I've looked a lot of examples but most of them only have pieces of the .php file to process it. I am trying to inject the "task" into the JSON file which I then use handlebars to read on another page.
function fnCreateTask() {
var url = "save.php";
var title = $("#TaskTitle").val();
var date = $("#TaskDate").val();
var desc = $("#TaskDescription").val();
var info = {
Title: title,
Date: date,
Description: desc
};
var body = JSON.stringify(info);
$.ajax({
type: "POST",
url: url,
contentType: 'application/json',
data: body,
dataType: 'json',
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
}
<?php
$fp = fopen('careers.json', 'w');
fwrite($fp, $_POST = json_decode(file_get_contents('php://input'), true););
fclose($fp);
?>
$.ajax POST (or GET for that matter) data will be x-form encoded by default when sent to the server. You can do
on the client
//object for the data
var data = {
title: $("#TaskTitle").val(),
date: $("#TaskDate").val()
};
$.ajax({
type: "POST",
url: "save.php",
data: data,
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
and on the server
// as a separate object to be safe
$dataobj['title'] = $_POST['title'];
$dataobj['date'] = $_POST['date'];
// write json_encode object to file
file_put_contents ( 'filename.json' , json_encode($dataobj));
To create a JSON in PHP :
<?php
$array = array(
"name" => "toto",
"lastname" => "lafraise",
"age" => 33
);
$fp = fopen('careers.json', 'w');
fwrite($fp, json_encode($array));
fclose($fp);

Categories