Download generated excel file with phpExcel as attachment when form is submitted in drupal 7 - drupal-7

This is my code. Form submits, but no file is downloaded as attachment. No errors
function dn_preorder_form_submit($form,&$form_state){
$excel = new PHPExcel();
$excel->setActiveSheetIndex(0);
$excel->getActiveSheet()->setCellValue('A1',"TEST");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="var.xlsx"');
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Cache-Control: nmax-age=0");
$file = PHPExcel_IOFactory::createWriter($excel,'Excel2007');
$file->save('php://output');
}
I have tried this solution
https://drupal.stackexchange.com/questions/103690/download-file-on-form-submission
But i still get same results.
I have tried this code outside drupal and it works

OK, i solved it by inserting exit() at the end of the code
function dn_preorder_form_submit($form,&$form_state){
$excel = new PHPExcel();
$excel->setActiveSheetIndex(0);
$excel->getActiveSheet()->setCellValue('A1',"TEST");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="var.xlsx"');
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Cache-Control: nmax-age=0");
$file = PHPExcel_IOFactory::createWriter($excel,'Excel2007');
$file->save('php://output');
exit();
}

Related

Why I get "SyntaxError: JSON.parse: " while using Laravel

I want to query few tables and return as JSON output for my mobile app.
public function index(){
$data['filters'] = Filters::orderBy('id','asc')->where('ftype', 'r')->get();
$data['categories'] = Category::where('status','=','A')
->where('parent_id',0)
->orderBy('name')
->get();
$data['requests'] = URequest::with('user.profile')
->whereIn ('requests.status', ['A','B'])
->orderBy('requests.created_at','desc')
->get();
$data['today'] = new Carbon(date("Y-m-d"));
return response()->json([
'success' => true,
'data' => $data
]);
}
When I run the above code on Postman, I get this error:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 265962 of the JSON data.
If I check the raw-data then it shows the data but also, some HTML error like
" Whoops, looks like something went wrong.".
This code should work but as a work around, I also tried: $data = array() at the beginning but it's not working either.
Could anybody please advise what I'm missing here?
Below is the code portion that I removed from the index.php that I had added to avoid jwt authentication.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: cache-control, content-type, Content-Type, Accept, Authorization, authorization");
header("Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS,FILES");
This snippet was causing this error:
"Cannot modify header information - headers already sent by (output started at /var/www/xx/public/live/vendor/symfony/http-foundation/Response.php:1286)"
and hence, was throwing that extra html to the browser:

Malformed JSON in slim framework

I have this in a route:
echo '{"result":{"code":"200","status":"success","data":'.$response->withJson($rows,200,0).'}}';
that returns this JSON:
{"result":{"code":"200","status":"success","data":HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8 [{"id":23,"ragionesociale":"consumatore","indirizzo":"000","comune":"000","provincia":71,"cap":"000","idprovincia_camera":71,"telefono":"000","fax":"000","sitoweb":"0","email":"info#000.it","codice_promo":"xxxxx","password":"xxxxx","data_adesione":"2014-09-26 07:52:23","attivato":1,"costo":0,"tipologia":1,"iva":22,"alias":"prova-it4italy-srl","pagamento":1,"merchantorderid":null,"mybankid":null,"pending":0,"paymentid":null,"logo":"","nome":null,"cognome":null,"sesso":1,"datanascita":null,"eta":null,"nazione":null,"tipologia_utente":1,"fb_token":null,"fb_id":null,"gp_token":null,"gp_id":null,"profile_img":null,"citta":null,"param":null}]}}
the problem is that I receive a second response header inside the data, that breaks the JSON.
I would like to have a response of this kind:
{"result":{"code":"200","status":"success","data":[{"id":23,"ragionesociale":"consumatore","indirizzo":"000",....
Is there a way in slim to do not print the HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8 part in the JSON?
In $response->withJson() the Content-Type of the Response is automatically set to application/json;charset=utf-8, along with the default 200 HTTP status code. So you don't have to add that manually.
See response->withJson()
So just doing the following should be sufficient.
$result = new stdClass();
$result->result = new stdClass();
$result->result->code = "200";
$result->result->status= "success";
$result->result->data = $rows;
echo $response->withJson($result);

Cant download file from webservice using MTOM and Axis2 stub

I m trying to download a file from my Axis2 webservice server using MTOM and ADB.
I can download the file if I dont enable the MTOM both on server and the client sides. Any suggestions or code sample would be nice :)
Client side
ServerWSStub stub = new ServerWSStub();
stub._getServiceClient().getOptions().setProperty(Constants.Configuration.ENABLE_MTOM,Constants.VALUE_TRUE);
Server side axis2.xml
<parameter name="enableMTOM">optional</parameter>
This is my Server
public DataHandler download(String konum) throws Exception {
System.out.println("The filePath for download: " + konum);
FileDataSource dataSource = new FileDataSource(konum);
DataHandler datahandler = new DataHandler(dataSource);
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace ns = fac.createOMNamespace("http://benim.projem.org/dosya", "dosyam");
OMText textData = fac.createOMText(datahandler, true);
OMElement ele = fac.createOMElement("sonuc", ns);
ele.addChild(textData);
System.out.println(ele);
return datahandler;
This is my Client
ServerWSStub stub = new ServerWSStub();
//stub._getServiceClient().getOptions().setProperty(Constants.Configuration.ENABLE_MTOM,Constants.VALUE_TRUE);
//when uncommented i get java.lang.NoClassDefFoundError: org/apache/james/mime4j/MimeException
//while trying to invoke _operationClient.execute(true); in ServerWSStub
//I guess it is because of wrong unparsing
Download download = new Download();
download.setKonum(konum);
try {
DownloadResponse downloadResponse = stub.download(download);
DataHandler dh =(DataHandler) downloadResponse.get_return();
File file = new File("C:/dosya/"+fileNameType);
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
dh.writeTo(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (ServerWSExceptionException e) {
e.printStackTrace();
}
Any
I finally got the solution I guess. The Stream closes before the client gets the whole file thats why first I used the getOptions().setTimeOutInMilliSeconds(10000) method but it was also useless and then in the Stub file I commented
_messageContext.getTransportOut().getSender().cleanup(_messageContext);//look for the method's finally part
part so that during a large file transportation the stream had not been closed and i could download the whole file without any silly exceptions :)
--MIMEBoundary_e56e8a77b94fbdd7678582aa5ca53f50b1d56c0d828499ea
Content-Type: application/xop+xml; charset=UTF-8; type="text/xml"
Content-Transfer-Encoding: binary
Content-ID: <0.146e8a77b94fbdd7678582aa5ca53f50b1d56c0d828499ea#apache.org>
<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><ns:downloadResponse xmlns:ns="http://servis.ws.projem.tez.benim"><ns:return><xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:1.046e8a77b94fbdd7678582aa5ca53f50b1d56c0d828499ea#apache.org" /></ns:return></ns:downloadResponse></soapenv:Body></soapenv:Envelope>
--MIMEBoundary_e56e8a77b94fbdd7678582aa5ca53f50b1d56c0d828499ea
Content-Type: text/plain
Content-Transfer-Encoding: binary
Content-ID: <1.046e8a77b94fbdd7678582aa5ca53f50b1d56c0d828499ea#apache.org>
binary code here
Simply add apache-mime4j-core-0.7.2.jar to WEB-INF/lib on the service (server) side. The jar can be found here.

Pop up the file to be download on clicking the link

I am trying to make the .txt, .xml,.sql files be downloadable in the same page just like .zip,.docx files which are pop up and ask "do you want to download this file?".
I have researched and found that the windows default option for these files are open in new browser but I just want to be download in the same page. I have attached the image just like that I need to pop up when clicking those .txt,.xml,.sql files.
How can this be done? Anyone have idea for this.
I have corrected by my own. Just putting the code below will successfully pop up any files to ask whether to download or not. This is my new code.
The download.php contains the code below:
<?php
$filename = $_GET["file"];
$contenttype = "application/force-download";
header("Content-Type: " . $contenttype);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
if($_GET['path'] == 'new_uploads')
readfile($_SERVER['DOCUMENT_ROOT']."50dl/admin_panel_new/assets/plupload/new_uploads/".$filename);
else
readfile($_SERVER['DOCUMENT_ROOT']."50dl/admin_panel_new/assets/plupload/assessment_uploads/".$filename);
exit();
?>
And the file.php contains this code:
<img src="<?php echo base_url();?>assets/plupload/assessment_uploads/<?php echo $files->file_name?>" title="DOWNLOAD IMAGE" height="100" width="100" onClick="window.location.href='<?php echo base_url();?>logos/download?file=<?php echo $files->file_name?>&path=assessment_uploads'" class="download"/>
This will correctly sort out the current issue.
You can use this and it will work like a charm .
<?php
$filename = $_GET["file"];
$contenttype = "application/force-download";
header("Content-Type: " . $contenttype);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
if($_GET['path'] == 'new_uploads')
readfile($_SERVER['DOCUMENT_ROOT']."50dl/admin_panel_new/assets/plupload/new_uploads/".$filename);
else
readfile($_SERVER['DOCUMENT_ROOT']."50dl/admin_panel_new/assets/plupload/assessment_uploads/".$filename);
exit();
?>
You should pass the headers in the code where file download is requested.
$task = isset($_REQUEST['task']) ? $_REQUEST['task'] : '';
if ($task == 'download'){
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($_REQUEST['file_name']));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($_REQUEST['file_name']));
ob_clean();
flush();
readfile($_REQUEST['file_name']);
exit;}

JavaMail PDF attachment shows up in garbled text or encoded text

I'm trying to send a PDF attachment through JavaMail, but when I receive the email, I get something like this, without any attachments in the mail:
===EMAIL CONTENT===
------=_Part_0_3786439.1313701770148
Content-Type: application/pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=ems_report.pdf
JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9MZW5ndGggMTE4Ni9GaWx0ZXIvRmxhdGVEZWNvZGU+
PnN0cmVhbQp4nLWaTW/jNhCG7/oVBIoF0kMYfgw/1FviZNsEa+/WVrCHogc3VgIXsb1VnS7670vK
lhynMjmxRQSOBA1JPXpfaTSSyAgn55wworlw/x8W2V/ZVZFJTZTRpJhlN0X2aybInd/q2zHStC4W
2cVHTvzaY3b2Y/Gnb7trUg/G6pXqKROMqFy4QRU5l25LmT2+HtFtUoZRadpRrR/VLd2f6352M5yQ
8ctyWq1eljMyWC2+Pc+ny4eSjMtvq2pNHlcVGd0WNx6DkacOlN9+d8tZfSjtsNttb1q+4sqBKG6p
5S0XeK72sM52TLfL+Xo+Xa+qv8nkZbGYVv8iWfYFozlwd/CvlpbJ3O/LszBLOGOdEnJmqLUEbE7l
zhxW41Ln7fa3D/1xXi0OYwry3UXutv21C4x/bti3NIuMb9ees4nr33Tw5JvfXhcwTRe/5rscKwUY
s5FCdEghBdWcgJYdUgBpfl6Kd5wzWDgeoROOzhuFoDPG5D3TQYROSUsBUHQSemZTETYNnAqBYhM9
o4kImnyHbLpnNhlhA+HYJIrNLTX5kOCCCGUuwTSFnECuKJfhzPW5mpUuwY7Lh3L+TzlrQPcuLTeS
lVT5gd52L1br6fPhowunL96mPIFOebzNeeLUnAcRFRVzSQ8l4i79b+R8q6KSLtnrwyp+mk//eC6P
lRFaGRVaRmhlVKfKqCIyaiejwp2MMR214PV5fUjH0Wp5/nySlqrVUqO1VK2W+lQtRURL2dspKVNe
===CODE===
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart part1 = new MimeBodyPart();
FileDataSource source = new FileDataSource("ems_report.pdf");
part1.setDataHandler(new DataHandler(source));
part1.setFileName(source.getName());
part1.setHeader("Content-Type", "application/pdf");
part1.setHeader("Content-Transfer-Encoding", "base64");
part1.setDisposition(Part.ATTACHMENT);
multipart.addBodyPart(part1);
MimeBodyPart part2 = new MimeBodyPart();
part2.setText("mimebodypart part2");
multipart.addBodyPart(part2);
message.setContent(multipart);
message.setHeader("Content-Type", "multipart/mixed");
What did I do wrong here? I've googled for the whole day and no one seems to have the solution. Any help is appreciated, thanks so much!
What you're seeing is a binary data of the multipart. You first have to decode the base64 string. After that you can process the PDF.
PS: If you open that mail in a client (Webmail, Outlook, Thunderbird) you should see the PDF correctly.

Resources