Start downloading zip automatically which was made by Ajax - php

I have a button which let server make zip file by Ajax.
$('.zipButton').click(function(){
console.log($(this).context.firstChild.data);
$(this).context.firstChild.data = "working......";
$(this).addClass('disabled');
var self = $(this);
$.post('{{path('acme_member_zip')}}',// make zip file on server.
function(response){
if(response.code == 100 && response.success){
console.log(response.message);
self.context.firstChild.data = "finish make zip";
alert("please download http://www.myserver.com/myzip/arc.zip");
}
else {console.log("no correct return");}
}, "json");
});
For now, after making zip I let user know where the zip file by alert.
However,I want to push on browser start downloading automatically.
How can I make it???

You can redirect the client to the ZIP url with document.location, like this :
$.post('{{path('acme_member_zip')}}',// make zip file on server.
function(response){
if(response.code == 100 && response.success){
console.log(response.message);
self.context.firstChild.data = "finish make zip";
document.location = "http://www.myserver.com/myzip/arc.zip";
}
else {
console.log("no correct return");
}
},
"json"
);

There are few way to achieve this.
1)
you can use the download attribute in the hyperlink
Your file Name
document.getElementById('download').click();
2)
Use the jQuery file Download plugin
https://github.com/johnculviner/jquery.fileDownload
3)
Set window.location = 'your file path'; after the success

Related

Read PDF from external URL, and automatically download when the button was triggered

I would like to download a pdf from my external URL, store it in my server and download it when the button was triggered by click by the user.
I have tried to store it to my server and its success, but then I don't know how to automatically download the pdf as the user wants after they click the button.
My view:
<button id=\"appPrintbutton\" name=\"appPrintbutton\" style=\"cursor:pointer;padding: 3px; margin: 2px;float:left;\" title=\"Cetak Dokumen\"><i class=\"fas fa-check fa-lg fa-fw\"></i>Cetak</button>
<script type="text/javascript">
$("#appPrintbutton").on('click', function() {
var selectedId=[];
selectedId.push(document.getElementById("txtNO_DOK").value);
$.ajax({
url: "<?php echo base_url().'index.php/finance/M_approve/DOWNLOAD_FILE_NILAI'?>",
type: 'POST',
data: {json: JSON.stringify(selectedId)},
dataType: 'json',
success: function (data) {
window.location.href = "<?php echo base_url().'index.php/finance/M_approve/';?>";
},
error: function (data) {
console.log('error');
}
});
return false;
});
</script>
And my Controller was:
public function DOWNLOAD_FILE_NILAI()
{
$msg="";
$status="";
$rptName="";
$pathdir="/wwwroot/php/download/";
$ieselon="ALL";
$data=$this->input->post('json');
$nodok=substr($data, 1, 9);
if($nodok!="" )
{
$randfname = Date("Y_m_d");
$fname = $nodok."_nilai".$randfname.".pdf";
$rptName="\wfinance\kas_cetak.rpt";
$strParamName= "&promptex-no_dok=".$nodok;
$strParamName.= "&promptex-terbilang=".$nodok;
$exportType="PDF";
$serverLink = "http://11.5.1.44:12000/ReCrystallizeServer/ViewReport.aspx?report=".$rptName;
$fullLink=$serverLink.$strParamName."&exportfmt=$exportType";
$fdata = file_get_contents($fullLink);
$fSaveAs=fopen($pathdir."$fname","w");
fwrite($fSaveAs, $fdata);
fclose($fSaveAs);
$status="OK";
}
$dataStatus[] = array(
'Status'=>$status,
'url'=>base_url(),
'fname'=>$fname,
'Msg'=>$msg
);
print_r(json_encode($dataStatus,JSON_PRETTY_PRINT));
}
My desired output:
Automatically download the pdf
Is it any way to do that?
You can use file_put_contents() function in PHP to read and write remote files to the server's directory.
$remote_file = 'http://example.com/path/to/pdffile.pdf';
$local_file = '/documents/new_file.pdf';
file_put_contents($local_file, file_get_contents($remote_file));
Update
If you are unable to write file directly, you can use two step way. First create blank file and after that write to it.
$local_file = fopen("/documents/new_file.pdf", "w")
This will create a file so other functions could write to it.
this way you can display files either from external/internal URL. And in case of downloading, you can provide local URL of /documents/new_file.pdf
So when the user clicks button you can hit ajax which triggers a server-side script which executes the code above.
Make sure your local directory /documents/ is writable by PHP process.
Read: https://www.php.net/manual/en/function.file-put-contents.php

Copy a multiple file from client system to server

I don't have any idea to copy a file from client system to server.
Short Description
I am using upload folder dialog box to upload a multiple file from particular path.
XML file is mandatory, because i need to extract some information to process
While upload event i read all the information i need to process
$("#myInput").change(function() {
var names = [];
var formData = new FormData();
for (var i = 0; i < $(this).get(0).files.length; ++i)
{
var F_name= $(this).get(0).files[i].name;
var extension = F_name.replace(/^.*\./, '');
if(extension != "xml" && extension != "db"){
formData.append('userfiles[]', $(this).get(0).files[i], F_name);
}
else if(extension == "xml"){
//Gathering info
}} });
User interface fields are filled automatically after this process and user have to fill some more fields. While user click process button in server side i create folder and some new XML files too. Everything is fine except , copy a file from client to server.
//Jquery
$("#process_but" ).click(function() {
$.ajax({
type: "POST",
url: "Asset/PHP/function.php",
data: {action: "action1", DOI:doi, TLA:tla, STITLE:S_Title, SHEAD:S_Head, SLINK:S_Link, LTYPE:link_type, DESC:description, ATITLE:Art_title, JTitle:JOU_title, ANAME:Author_name, FSHARE:Fig_share, FNAMES:filenames, FCOUNT:filecount},
success: function(response) {
if(response == 1)
{alert("success");}
else
{alert("Something goes wrong.....");}
},
error: function() {
alert("Error");
}
});
});
//php
<?php
session_start();
$action = $_POST['action'];
if($action == "action1")
{
//what i have to do
}
?>

exit from parent function according to ajax success callback return value

//this function will upload file through ajax
add: function (e, data) {
//before upload file check server has that file already uploaded
$.ajax(
{
type: "POST",
dataType:'json',
url:"../admin/cgi/file_check.php",
async:false,
data:{
filename : upload_filename,
docname : upload_docname,
userid : upload_userid,
},
success:function(data)
{
//check file alreay exists
if(data['doc_name'] == 'invalid')
{
// if file alreay exists want to stop upload process
//exit from main funtion
}
},
error:function(request,errorType,errorMessage)
{
alert ('error - '+errorType+'with message - '+errorMessage);
}
});
//file uploading code
}
add: function (e, data) {} - main function upload file through ajax
before upload check server has that file already uploaded through ajax request
if file alreay exists ajax success call back return the value data['doc_name'] = 'invalid'
if file alredy exists if(data['doc_name'] == 'invalid') i want to stop uploading proccess (want to exit from main uploading function)
You can try this: If your ajax returns invalid then display error message otherwise upload file.
success:function(data)
{
//check file alreay exists
if(data['doc_name'] != 'invalid')
{
//file uploading code
}
else
{
// Display your error message.
}
},

Dropzone.js remove button with php

I use dropzone.js for a nice upload form.
I linked the php code to upload the files and i setted addRemoveLinks=true so i have the remove button.
I need an idea how to efectivly delete the filse uploaded with a php code when i hit remove button.
The php is simple to do but i need t know how to relate them.
I already tryed using $.post in this function removedfile: function(file) but no succes.
removedfile: function(file) {
$.post("test.php");
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
First off, you shouldn't simply overwrite the default removedfile event handler, but rather register your own handler along with it.
You need to first get the ID back from the server (so you know how to relate to it) and then use this to setup the delete call.
Dropzone.options.myDropzone = {
init: function() {
this.on("success", function(file, response) {
file.serverId = response; // If you just return the ID when storing the file
// You can also return a JSON object then the line would
// look something like this:
//
// file.serverId = response.id;
//
// In that case make sure that you respond with the mime type
// application/json
});
this.on("removedfile", function(file) {
if (!file.serverId) { return; } // The file hasn't been uploaded
$.post("delete-file.php?id=" + file.serverId); // Send the file id along
});
}

Upload Image using ajaxupload

I am using Ajax Upload for file upload via ajax and php.
At js file i wrote following line of code:
$(document).ready(function() {
if ($('#uploadExists').length) {
var btnUpload = $('#uploadExists');
var u = new AjaxUpload(btnUpload, {
action: '/upload',
name: 'fname',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
//Bad file
return false;
}
},
onComplete: function(file, response){
if (! (/(\.jpg|\.png|\.jpeg|\.gif)/.test(response))) {
//Bad file
console.log(response);
return false;
} else {
console.log(response);
}
}
});
}
});
At /upload url what should I do?
I am writing things in PHP.
At /upload (for instance /upload/index.php) you receive the file via the $_POST variable. Try doing var_dump($_POST) to see what the filename is. Then you can use http://php.net/manual/en/function.move-uploaded-file.php to move the file as you would like. This script will be sent 1 file at a time from the multi-file upload, so you handle the upload as if you were handling a single upload via a standard html form.

Categories