Download pdf vuejs from API Laravel - php

hello I have a frontend with VUEJS and backend Laravel 5.4.
I would download a pdf saved in storage/folder/file.pdf
Now I make a ajax call from VUEJS:
downloadAttachment(){
axios.get('/url/attachment/' + this.resource.id)
.then(function (response) {
})
.catch(function (error) {
});
}
and in backend I have a function that return pdf file:
public function download(){
$headers = array(
'Content-Type: application/pdf'
);
return response()->download(storage_path('folder/file.pdf'), 'namefile.pdf' , $headers)->setStatusCode(200);
}
But now How Can i show an Iframe for download in frontend?
I tried with:
var blob = new Blob([response.data],{type:headers['content-type']});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Filename";
link.click();
But it doesn't work, How can i show in frontend iframe with pdf file download?

Try this: window.open(URL).
Here the "URL" should be the actual URL string so probably you will have to change the response of the controller to something like: return response()->json(<url string>)

Related

How to download image using vue js and laravel

I have a hyperlink button on click of this, i want to fetch image from database and get it downloaded on user side with use of laravel and vue js. Below is my code for script file
getImage: function() {
axios.get('/getImage/' + this.form.cashout_id )
.then(function (r)
{
const url = window.URL.createObjectURL(new Blob([r.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.'+r.headers.ext); //or any other extension
document.body.appendChild(link);
link.click();
//hide loader
i.loader = false
})
.catch(function (error) {
alert('Error');
});
},
and now this is my controller code where image is being fetched.
public function getimage($id)
{
$cashout = CashOutDetail::findorfail($id);
$storage_date = Carbon::parse($cashout['recorded_date']);
return response()->download(
storage_path('app/cashoutdetails/'. $storage_date->year .'/' . $storage_date->format('M') . '/'. $cashout->bank_receipt),
'filename.jpg',
['Content-Type' => 'image/jpg']
);
}
Issue is that my image is being fetched and displayed in console window but unable to download. Can anybody help?
You should try:
axios({
method: 'GET',
url: '/getImage/123.jpg',
responseType: 'blob', // <-<<<<<<<<<<
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', '123.jpg');
document.body.appendChild(link);
link.click();
});

Display image url use AXIOS combine with laravel

now im doing AXIOS code combine with laravel to get image from instagram URL. the URL is this https://www.instagram.com/p/B_zZCRpB895/media/?size=t
AXIOS is new from me. to get the image, i tried this simple code. i set this code into my frontend site
<img id="imgsrc" src="" >
<script>
axios
.get('https://www.instagram.com/p/B_zZCRpB895/media/?size=t', {
responseType: 'arraybuffer'
})
.then(response => {
const buffer = Buffer.from(response.data, 'base64');
document.getElementById("imgsrc").src = Buffer;
console.log(Buffer);
})
.catch(ex => {
console.error(ex);
});
</script>
but the image not display into <img id="imgsrc" src="" >
i really want that, when we open the page. the instagram image can display.
how to solve this matter. please help.
you can use file reader to get base64 and set it as the image source :
<script>
axios.get('https://www.instagram.com/p/B_zZCRpB895/media/?size=t', {responseType: "blob"})
.then(function (response) {
var reader = new window.FileReader();
reader.readAsDataURL(response.data);
reader.onload = function () {
document.getElementById("imgsrc").src = reader.result;
}
});
</script>
Is there a particular reason you are retrieving this via an AJAX call using axios?
The endpoint you provided returns an image source already. To make it appear in the image element all you need to do is set the src to the endpoint URL as shown below. Unless you need to run a process to do something to the image you don't need to get the data as an array buffer.
document.getElementById("imgsrc").src = "https://www.instagram.com/p/B_zZCRpB895/media/?size=t";

View pdf stream in browser

I have a PDF file that I want to view in browser tab. I know that I can use file link directly to display it, but I want to read contents of file in a variable and use the variable to display file. Reason behind is, I want to delete the file immediately after reading in variable.
PHP:
$fdata = file_get_contents($tmppdf);
header("Content-type: application/pdf");
header("Content-disposition: inline; filename=".$tmppdf);
return $fdata;
Ajax:
$('body').on('click', '.printInvoice', function () {
var purchase_id = $(this).data("id");
// window.location.href = "/purchases/print" + '/' + purchase_id;
window.open('/purchases/print' + '/' + purchase_id, '_blank');
});
I am getting binary contents in result. Can someone help, what is wrong with my code.
UPDATE :
Changed my ajax code to below and now I am getting a blank pdf page
$('body').on('click', '.printInvoice', function () {
var purchase_id = $(this).data("id");
$.ajax({
type: "GET",
url: "/purchases/print" + '/' + purchase_id,
success: function (data) {
var blob = new Blob([data], {type: 'application/pdf'});
var blobURL = window.URL.createObjectURL(blob);
window.open(blobURL,'_blank');
},
error: function (data) {
alert("Unable to Print !!!");
}
});
Perhaps:
return Response::make($fdata, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$tmppdf.'"'
]);
Laravel actually has built-in functionality to return file responses. This will automatically set the correct headers so the file gets displayed in the browser.
return response()->file($tmppdf);
If you want to stream the file you can use this to display the file:
This worked with a binary string.
return Response::make($file, 200, [
'Content-Type' => 'application/pdf',
]);

Angular 6 CSV download

I'm new to angular, currently i'm working in a project which needs an csv export. Here i'm using Angular 6 as frontend and laravel as backend
This is how i wrote laravel function using mattwebsite/excel
// Lead export to csv
public function downloadExcel(Request $request)
{
$credentials = $request->only('token');
$token = $credentials['token'];
$userid = $this->getUseridFromToken($token);
$type = "xls";
$data = DB::table('user_mailbox AS A')
->select('A.id', 'A.name', 'A.email', 'A.phone', DB::raw('DATE_FORMAT(A.send_on, "%d / %b / %Y") as send_on'), 'B.listing_heading','B.listing_id','B.listing_heading', 'C.name')
->leftjoin('broker_listing AS B', 'B.listing_id', '=', 'A.listing_id')
->leftjoin('users AS C', 'C.id', '=', 'A.sent_by')
->where('A.sent_to', $userid)
->where('A.user_type', '1')
->orderBy('A.id', 'desc')->get()->toArray();
Excel::create('Lead_Export', function($excel) use ($data) {
$excel->sheet('Lead_Export', function($sheet) use ($data)
{
$sheet->fromArray($data);
});
})->download($type);
}
This is how i wrote function in angular component
// Download leads as excel
download_excel(){
const fd = new FormData();
fd.append('token',this.token);
this.brokerleads.downloadLeads(fd).subscribe(
data => this.handleResponsedwnload(data),
error => this.handleErrordwnload(error)
);
}
handleResponsedwnload(data){ console.log('test');
const blob = new Blob([data], { type: 'text/xls' });
const url= window.URL.createObjectURL(blob);
window.open(url);
}
handleErrordwnload(data){
}
service is like this
// Download as excel
downloadLeads(data):Observable<any>{
return this.http.post(`${this.baseUrl}downloadExcel`, data);
}
view
<a class="export-leads" href="javascript:void(0);" (click)="download_excel()" >EXPORT LEADS</a>
while doing this i'm getting response like this but file is not downloading
You need to navigate the browser to the route where the Excel file is made on the backend (in a new tab) either with a link <a href="path" target="_blank"> or with window.open
The ->download() function sets headers so that the file will be automatically downloaded.
When you fetch this data with an AJAX call (which is what HttpClient does) you simply get the binary data returned (which is what you see in your Response tab in Chrome developer tools).
(There are front-end hacks to download a file retrieved by ajax such as creating a link element and clicking it with JavaScript (see below), but they can not be recommended):
let fileName = 'filename.xlsx';
let a = document.createElement('a');
a.href = window.URL.createObjectUrl(responseData);
a.download = fileName;
a.click();
This can also be done using file-saver:
import * as FileSaver from 'file-saver';
this.http.post(`${this.baseUrl}downloadExcel`, data, { responseType: 'blob' })
.subscribe((resp: any) => {
saveAs(resp, `filename.csv`)
});
This function working for me to export csv,
downloadFile(data: any) {
const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
const header = Object.keys(data[0]);
let csv = data.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
csv.unshift(header.join(','));
let csvArray = csv.join('\r\n');
var a = document.createElement('a');
var blob = new Blob([csvArray], {type: 'text/csv' }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "myFile.csv";
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}

Force download image file that's returned as http response using laravel, vue, axios and intervention image

I am trying to set up a media asset database using Laravel, Vue, Axios and Intervention image.
I want the user to be able to set a desired image height and width before downloading an image. This is then sent to the controller using an axios post-request. Inside the controller, intervention image is working its magic(k) and returning my resized file as a response.
Now I want the image that's being returned as a response to trigger a download. What do I need to do with my axios-response?
Here's what I currently have:
Axios-Request:
resize(file) {
this.file = file;
let formData = new FormData();
formData.append('imageHeight', this.imageHeight);
formData.append('imageWidth', this.imageWidth);
axios.post('files/resize/' + file.id, formData).then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
this.errors = error.response.data.errors;
this.showNotification(error.response.data.message, false);
this.fetchFile(this.activeTab, this.pagination.current_page);
});
}
Controller:
public function resize($id, Request $request)
{
$file = File::where('id', $id)->where('user_id', Auth::id())->first();
$originalImage = $file->getName($file->type, $file->name, $file->extension);
$originalImagePath = Storage::get($originalImage);
$imageHeight = $request['imageHeight'];
$imageWidth = $request['imageWidth'];
if ($img = Image::make($originalImagePath)) {
return $img->resize($imageWidth,$imageHeight)->response();
}
}
You'll want the Content-Disposition response header to be attachment rather than inline.
http://image.intervention.io/use/http

Categories