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 '';
}
Related
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);
}
});
});
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'];
I have multiple uploads on a page, and I am workin on tidying it up, so:
Here's my js:
$(".img").change(function () {
var form = $(this).closest('form');
getPath(form);
})
deleteButton();
copyGalleryData();
});
function getPath(form) {
var name = $(form).attr('name');
submitImage(form, name);
}
var path_to_delete;
function submitImage(form, name) {
var url = '/image/upload';
var form_data = new FormData($(form)[0]);
submit(name);
form_data.append('img', $(form).children(".img"));
$.ajax({
url: url,
data: form_data,
dataType: 'json',
async: true,
type: 'post',
processData: false,
contentType: false,
success: function (data) {
console.log(data);
$(form).children('.image-container').append('<img id="image" name=' + name + '" src="' + data + '" />')
$(".imageDelete").attr('data', data);
alerts();
var deleting = false;
success(name, deleting, data);
$('.messages').html('<div class="alert alert-success">Image Uploaded!<div>');
},
error: function (data) {
alerts();
fail();
$('.messages').html('<div class="alert alert-danger">File type not supported! Use files with image extension only!</div>');
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
and controller:
class ImageController extends Controller
{
use S3;
public function upload(ImgRequest $request)
{
if ($request->hasFile('img')) {
$this->imageEntity();
return response()->json($path);
}
if ($request->hasFile('coverUpload')) {
$this->imageCover();
}
}
public function imageEntity()
{
$s3Path = config('app.path', public_path());
$image = Input::file('img');
Log::info('Retrieving Image', ['image' => $image]);
$filePath = 'public/logo/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$update_image = Entity::find($session);
$update_image->logo = $path;
$update_image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return response()->json($path);
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
public function imageCover()
{
$s3Path = config('app.path', public_path());
$image = Input::file('coverUpload');
Log::info('Retrieving Cover', ['image' => $image]);
$filePath = 'public/cover/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$image = new Images;
$image->path = $path;
$image->cover = true;
$image->entity_id = $session;
$image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return $path;
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
Now the funny thing is response is 200, however it is empty ($path is defined) and ajax is triggering error: part of the code and not success. I have checked the log, and try has been successful:
[2017-10-16 11:22:01] local.INFO: Retrieving Image {"image":"[object]
(Illuminate\Http\UploadedFile: /tmp/phpHPchM4)"} [2017-10-16
11:22:01] local.INFO: Adding to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully added to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully saved logo for {"entity_id":"324"}
Could anyone please help me solve this matter?
Update::
I have updated the controller so that the function returns $path, and main function return the response, however for some reason it is saying that $path is undefined, how to pass data from return to controller that is returned it?
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);
I want to copy file from google drive to another server using php.
I have used google drive picker and when user clicks on any file I used to get download url, I was thinking that it can be done through copy function, but it didn't work.
Any solution Please.
function getDownloadurl(fileId) {
var request = gapi.client.request({
'path': '/drive/v2/files/' + fileId,
'params': { 'maxResults': '1000' },
callback: function (responsejs, responsetxt) {
var fileDownloadUrl = responsejs.downloadUrl;
$.ajax({
type: "POST",
url: "ajax-files/copy_drive_file.php",
data: { gd_url:fileDownloadUrl },
async:false,
success: function(data)
{
}
});
copy_drive_file.php
$sourcePath=$_POST['gd_url'];
copy($sourcePath, 'sss/file.jpg');
You need to authorize and authenticate your requests while fetching from PHP
YourJsFile
function getDownloadurl(fileId) {
var accessToken = gapi.auth.getToken().access_token;
var request = gapi.client.request({
'path': '/drive/v2/files/' + fileId,
'params': {
'maxResults': '1000'
},
callback: function(responsejs, responsetxt) {
var fileDownloadUrl = responsejs.downloadUrl;
$.ajax({
type: "POST",
url: "ajax-files/copy_drive_file.php",
data: {
gd_url: fileDownloadUrl,
accessToken: accessToken
},
async: false,
success: function(data) {
console.log(data);
}
});
}
});
}
copy_drive_file.php
if ( isset($_POST['gd_url']) && isset($_POST['accessToken'])) {
$url = $_POST['gd_url'];
$accessToken = $_POST['accessToken'];
$opts = array(
'http'=>array(
'method'=>"GET",
'header' => "Authorization: Bearer " . $accessToken
)
);
$context = stream_context_create($opts);
$content = file_get_contents($url, false, $context);
if (!empty($content)){
file_put_contents("path/filename.file_extension",$content);
echo json_encode(array('file_name' => "filename.file_extension"));
}
}
Maybe this will help?
function copyFile($service, $originFileId, $copyTitle) {
$copiedFile = new Google_Service_Drive_DriveFile();
$copiedFile->setTitle($copyTitle);
try {
return $service->files->copy($originFileId, $copiedFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}