File is not being downloaded on Laravel5 using Response - httpresponse

I use Laravel 5.1.
A jQuery ajax call is made like that:
$('#export_selected').click(function(){
var checked = $('.select_rows:checked');
var ids = [];
$.each(checked, function(index, value){
ids.push(value.id);
})
$.ajax({
method : "POST",
url : "{{URL::to('/spot/exportTable')}}",
data : {ids:ids}
});
});
And then the php method is defined that way:
public function exportTable(Request $req) {
$spots = array_flatten($req->all());
$res = Spot::whereIn('id', $spots)->get();
Excel::create('Spots', function($excel) use($res) {
$excel->setTitle('Title goes here');
$excel->setCreator('Creator Goes Here')->setCompany('Company Goes Here');
$excel->sheet('Excel sheet', function($sheet) use($res) {
$sheet->setOrientation('landscape');
$sheet->fromArray($res);
});
})->store('csv', storage_path('/exports', true));
$file = base_path() . '/storage/exports/Spots.csv';
$headers = ['Content-Type: application/csv', 'Content Description: File Transfer', 'Cache-Control: must-revalidate, post-check=0, pre-check=0'];
return response()->download($file, 'Spots.csv' , $headers);
}
Chrome developer console prints the results as raw lines.
The file is successfully exported and created in the disk.
The path to file is correct.
But the download is never started.
Echoing the response gives:
HTTP/1.0 200 OK
0: Content-Type: application/csv
Cache-Control: public
Content-Disposition: attachment; filename="Spots.csv"
Date: Mon, 26 Oct 2015 16:08:26 GMT
Last-Modified: Mon, 26 Oct 2015 16:08:26 GMT
1: Content-Description: File Transfer
2: Cache-Control: must-revalidate, post-check=0, pre-check=0

I put the answer here for everybody having the same issue.
#manix figured it out: I'm trying to download via Ajax, which needs to be done in another way, not the way I wrote my code

Related

Angular 8 get txt file with auth header

I'm trying to implement a download link for users to download a record in .txt file.
Firstly it was a simple <a> tag
download
I could download the file from server in .txt format. But I found that it does not bring Auth header. So I tried to use a http get method to fetch it.
service.js
getCdrFile(url) {
return this.http.get<any>(`${this.env.service}/service/api/downloadFile?` + url);
}
component.js
downloadFile(url) {
this.service.getCdrFile(url).subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
}
);
}
I can successfully call the API with auth head, then I got nothing happened after I clicked the download button but the txt data displayed in the "response" tab in Chrome developer tool. Also, I got nothing from console.log(data); inside my http request.
Is there anyway I can download the file? thanks!
(and here is my response detail)
# GENERAL
Request URL: http://localhost:8080/service/api/downloadFile?fileType=daily&trsDate=20190918
Request Method: GET
Status Code: 200
Remote Address: 127.0.0.1:8080
Referrer Policy: no-referrer-when-downgrade
# RESPONSE HEADER
Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Disposition: attachment; filename=20190918.txt
Content-Type: application/json
Date: Wed, 02 Oct 2019 03:51:01 GMT
Expires: 0
Pragma: no-cache
Server: nginx/1.15.2
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
You can create a Blob response and create a blob url with it and download on the fly.
Service:
Modify your service to receive a blob response
getImage() {
return this.httpClient.get(
your_image_link,
{
responseType: 'blob', // <-- add this
headers: {your_headers}
}
);
}
Component:
On click of your link on the page call your service to get the response blob of your file
Create a blob url URL.createObjectUrl method
Create a dummy anchor element assign the blob url and name of the file to download
Trigger a click event on the anchor element
remove the blob url from browser using URL.revokeObjectUrl method
downloadImage() {
this.service.getImage().subscribe(img => {
const url = URL.createObjectURL(img);
const a = document.createElement('a');
a.download = "filename.txt";
a.href = url;
a.click();
URL.revokeObjectURL(url);
});
}
Stackblitz: https://stackblitz.com/edit/angular-kp3saz
You have two ways to download the file from the server.
1:-) Ater getting a response from HTTP call to create base64 and create a dummy anchor tag and download.
2:-) Modify backend response as download response.

Zend Http Client Reponse header data?

I get json file content using the zend http client in magento.
I don't need header info on getBody(). I did test it on some host where it works. But the live host gives me troubles.
$request_url = "link";
$httpClientConfig = array('maxredirects' => 0);
$client = new Zend_Http_Client($request_url, $httpClientConfig);
$client->setMethod(Zend_Http_Client::GET);
try {
$response = $client->request();
} catch (Exception $e) {
Mage::throwException($this->__('Gateway request error: %s', $e->getMessage()));
}
Mage::log($response->getBody());
Result logging:
2015-01-08T09:12:46+00:00 DEBUG (7): HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 761
Connection: close
Date: Mon, 05 Jan 2015 22:53:40 GMT
Last-Modified: Sat, 15 Nov 2014 10:14:17 GMT
ETag: "a8b17a42b7ef7e5960f9bd325a8c1892"
Accept-Ranges: bytes
Server: AmazonS3
Age: 5574
X-Cache: Hit from cloudfront
Via: 1.1 522dd06c4c8acf822ccbebe21aee8d1c.cloudfront.net (CloudFront)
X-Amz-Cf-Id: c6K9QJnOESg1NERKjG-v2fX_9eskmCzz_KUYdXrOb2NSjVTbWZ_x8Q==
{
"assets": {
"standard": {
"url": "https://d3k1w8lx8mqizo.cloudfront.net/standard.png",
"infobox": {
"page1": "https://d3k1w8lx8mqizo.cloudfront.net/frontside.png",
"page2": "https://d3k1w8lx8mqizo.cloudfront.net/backside.png"
}
},
"promotion": {
"infobox": {
"page1": "https://d3k1w8lx8mqizo.cloudfront.net/frontside.png",
"page2": "https://d3k1w8lx8mqizo.cloudfront.net/backside.png"
},
"url": "https://d3k1w8lx8mqizo.cloudfront.net/standard.png",
"interest_free_months": 6,
"transaction_limit_min": 240.0
}
}
}
Try this:
Zend_Http_Response::extractBody($response->getBody());
Or don't retrieve the headers in the request when instantiating the Zend_Http_Client:
$httpClientConfig = array(
'maxredirects' => 0,
'curloptions' => array(CURLOPT_HEADER => false),
);
If the above doesn't work, you can try an alternative way of doing the request such as file_get_contents:
$response = file_get_contents($request_url);
I hope it helps.

Parse.com Analytics not showing

I'm trying to connect to Parse.com 's REST-API via NSURLConnection to track AppOpened metadata.
I get 200 OK back from the API and the headers are the same to the cURL headers but my API calls are not being represented in the data browser on Parse.com . Is NSURLConnection doing something silly I don't know of? API response is the same but one request gets represented while the other one isn't.
NSLog output:
<NSHTTPURLResponse: 0x7ff5eb331ca0> { URL: https://api.parse.com/1/events/AppOpened } { status code: 200, headers {
"Access-Control-Allow-Methods" = "*";
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 3;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sun, 04 Jan 2015 22:42:54 GMT";
Server = "nginx/1.6.0";
"X-Parse-Platform" = G1;
"X-Runtime" = "0.019842";
} }
cURL output:
HTTP/1.1 200 OK
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Date: Sun, 04 Jan 2015 23:03:51 GMT
Server: nginx/1.6.0
X-Parse-Platform: G1
X-Runtime: 0.012325
Content-Length: 3
Connection: keep-alive
{}
It's the same output. What am I doing wrong? Has anyone experience with this?
Turns out Parse was showing funny API keys the moment I copied them out of the cURL example they provide in their lovely docs. Don't know whose analytics I screwed over but I'm terribly sorry and it wasn't my fault!
Always copy your API keys out of [Your-Parse-App-Name]->Settings->Keys
It probably was just a stupid glitch that happened on the Server.

Broken Image Replace using http response headers

I want to hide the broken image icon, but the image server that i'm using doesn't throw a 404 page, instead it redirects it to their alternative image, so I can't use the conventional onerror method.
This method works well if the server throws a 404 page in response.
<html>
<body>
<div><img src="http://stackoverflow.com/image.jpg" alt="image" onerror="this.style.display='none'"/></div>
</body>
</html>
but in conditions like, where image URL is: http://tinypic.com/someimage.jpg
the above method won't work. because this is a 302 response, which redirects it to some other image. I want to hide that as well.
Is that possible to somehow use http response as condition to display/hide image.
Here are http headers of the above image:
$ curl -I http://tinypic.com/notfound.jpg
HTTP/1.1 302 Found
Server: Apache
Location: http://tinypic.com/images/404.gif
Expires: Fri, 21 Mar 2014 21:33:07 GMT
Cache-Control: max-age=300
Content-Type: text/html; charset=iso-8859-1
Content-Length: 217
Accept-Ranges: bytes
Date: Fri, 21 Mar 2014 21:28:07 GMT
X-Varnish: 1535787681
Age: 0
Via: 1.1 varnish
Connection: keep-alive
X-Varnish-Server: den2tpv01
X-Cache: MISS
Now, I think HTTP/1.1 302 Found can be used in someway. any suggestions?
Here you go, the simple solution:
<img src="www.google.com/noanyimage.png" width="200px" height ="200px" onerror="this.src ='';" />
Here is the solution using php...
<?PHP
$url = "http://tinypic.com/notfound.jpg"; //Image link here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
$status_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($status_code==302 or $status_code==301 or $status_code==404){
echo "no image found";
}
else {
echo '<img src="'.$url.'" />';
}
curl_close($ch);
?>

CouchDB: Get server-time with an http request in CouchApp

I need the server-time for "user-is-online" stats in my CouchApp. I work with jquery.couch.js and would prefer to have a url, e.g. /db/_design/app/time - which gets me a timestamp.
How do I realize this?
A show function could do that:
function(doc, req) {
// _design/myapp/_show/now
// First version possibly incompatible with some spidermonkey versions.
//var now = new Date();
var now = new Date().getTime();
var output = JSON.parse(JSON.stringify(now)) + "\n";
return { code: 200
, headers: { "Content-Type": "text/plain"
}
, body:output
};
}
The server also includes a Date header that you might want to use.
$ curl -D- http://localhost:5984
HTTP/1.1 200 OK
Server: CouchDB/1.1.0 (Erlang OTP/R14B)
Date: Fri, 27 May 2011 00:28:31 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 40
Cache-Control: must-revalidate
{"couchdb":"Welcome","version":"1.1.0"}

Resources