Return image from controller in symfoy2 - symfony

I've looked at this question but it doesnt work for me.
my controller looks like:
/**
* #Route("/testing")
*/
public function trackingNewsletter() {
$filename = 'T:\wamp\www\trendytouristmx\web\uploads\establishments\1-37.jpg';
$response = new \Symfony\Component\HttpFoundation\Response();
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', mime_content_type($filename));
$response->headers->set('Content-Disposition',
'attachment; filename="' . basename($filename) . '";');
$response->headers->set('Content-length', filesize($filename));
$response->sendHeaders();
$response->setContent(file_get_contents($filename));
return $response;
}
But in the browser code is displayed instead of the image displayed:
browser looks like this
Thank you.

There is a special class which is designed for binary file response. I would recommend to use it instead. More info BinaryFileResponse
//$filePath = ...
//$filename = ...
$response = new BinaryFileResponse($filePath);
$response->trustXSendfileTypeHeader();
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$filename,
iconv('UTF-8', 'ASCII//TRANSLIT', $filename)
);
return $response;

You have to do :
public function trackingNewsletter() {
$path = 'T:\wamp\www\trendytouristmx\web\uploads\establishments\1-37.jpg';
$response = new Symfony\Component\HttpFoundation\Response();
$response->headers->set('Content-type', mime_content_type($path));
$response->headers->set('Content-length', filesize($path));
$response->sendHeaders();
$response->setContent(readfile($path));
}

Thank you #chalasr, finally it works, here's a solution:
first, I removed $response->headers->set('Cache-Control', 'private');
second, I changed the value of Content-Disposition from attachment to inline.
/**
* #Route("/tracking")
*/
public function trackingnewsletterAction() {
$filename = '...\establishments\1-39.jpg';
$response = new \Symfony\Component\HttpFoundation\Response();
$response->headers->set('Content-type', mime_content_type($filename));
$response->headers->set('Content-Disposition',
'inline; filename="' . basename($filename) . '";');
$response->headers->set('Content-length', filesize($filename));
$response->sendHeaders();
$response->setContent(file_get_contents($filename));
return $response;
}

Related

Image from url is a string not UploadFile instanceOf ¿why?

I'm looking for a solution to this issue for a long time.
This is an img => https://www.siweb.es/images/logo-light.png
I want to store this image as zip file usin OneupUploaderBundle.
So, when i get the image from Url usin file_get_contents or CURL it returns the image correctly but when i pass this file to $zip->addFile(); or an uoload service using Symfony\Component\HttpFoundation\File\UploadedFile both returns an error cause they are receiving a string as first Parameter.
I guess the problem is the file is not an instanceOf UploadeFile but i don't know how to convert it or use Filebag without a form.
public function testAction(Request $request){
$term = 'https://www.siweb.es/images/logo-light.png';
$image = $this->getimg($term);
if ($image instanceof UploadedFile){
$upload = $this->get('pablo.file_upload_service')->uploadZipFile($image,'test');
}
return $this->render('#pabloUser/Test/zip_test.html.twig',['upload' => $image]);
}
private function getimg($url) {
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
And the service:
public function uploadZipFile(UploadedFile $file,$folder){
// Check if the file's mime type is in the list of allowed mime types.
if (!in_array($file->getClientMimeType(), self::$allowedMimeTypes)) {
$this->pushbulletService->notification('Error en la subida de archivos',sprintf('Files of type %s are not allowed.', $file->getClientMimeType()));
throw new \InvalidArgumentException(sprintf('Files of type %s are not allowed.', $file->getClientMimeType()));
}
// Generate a unique filename based on the date and add file extension of the uploaded file
$filename = sprintf('%s/%s.%s', $folder, uniqid(), $file->getClientOriginalExtension());
$zipname = 'file.zip';
$zip = new \ZipArchive();
$zip->open($zipname,\ZipArchive::CREATE);
$zip->addFile($file);
$zip->close();
$adapter = $this->filesystem->getAdapter();
$adapter->write($filename, $zipname);
return $filename;
}
The problem is that your result from getimg is a (binary) string containing the image data. In order to pass it on as an UploadedFile you have to store the image in a (temporary) file first and then pass the path to it in the constructor.
It could look something like this:
$data = $this->getimg(...);
file_put_contents(sys_get_temp_dir() . '/filename.jpg', $data);
$image = new UploadedFile(
sys_get_temp_dir() . '/logo-light.png',
'logo-light.png'
);
$upload = $this->get('pablo.file_upload_service')->uploadZipFile($image,'test');

Symfony getRootDir() + /../folder/file.ext (file_get_contents) not found

I am virtually at a brick wall with Symfony, I have a folder at /../compiled/ with some minified files, and the controller is configured to get files from getRootDir() + /../compiled/file.min.css
However, it just throws out an exception 'file not found' when call file_get_contents(file) even when the file actually exists.
I just don't know what is wrong, it is such a cryptic problem.
Code as requested:
public function atpInitAction(Request $request) // Validates the origin.
{
$content = null; $_file = $request->query->get('file');
if ($_SERVER["SERVER_NAME"] == atpHandler::getDomain())
{
// I AM FROM THE ORIGIN...
$webfolder = $this->get('kernel')->getRootDir() . '/../compiled';
$_file = $webfolder."/".$_file;
}
// What's my mime?
$_mime = 'text/plain';
if ($_file[strlen($_file)-2] == 'j') { $_mime = 'text/javascript'; }
else { $_mime = 'text/css'; }
$response = new Response();
$response->headers->set('Content-Type', $_mime);
$response->headers->set('Content-Disposition', 'filename="'.basename($_file) . '";');
$response->headers->set('Content-Length', filesize($_file));
$response->setContent(file_get_contents($_file));
$response->sendHeaders();
return $response;
}

\u0022 instead of " " with JsonResponse symfony

my problem is :
The data returned have \u0022 instead of "".
$em=$this->getDoctrine()->getManager();
$result = $em->getRepository('HomeBundle:Product')->findAll();
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$jsonContent = $serializer->serialize($result,'json');
$response = new JsonResponse($jsonContent);
$response->headers->set('Content-Type', 'application/json');
return $response;
and that's what i get
"[{\u0022id\u0022:1,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:3},{\u0022id\u0022:2,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:5},{\u0022id\u0022:3,\u0022name\u0022:\u0022oppv\u0022,\u0022price\u0022:16},{\u0022id\u0022:4,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:6},{\u0022id\u0022:5,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:7},{\u0022id\u0022:6,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:34},{\u0022id\u0022:7,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:56},{\u0022id\u0022:8,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:30}]"
thanks in advance for your help
As your entities are already serialised, change your JsonResponse to a Response :
use Symfony\Component\HttpFoundation\Response;
// ...
$response = new Response($jsonContent);
$response->headers->set('Content-Type', 'application/json');
return $response;
Or decode your results before create your JsonResponse :
return new JsonResponse(json_decode($jsonContent));
Note that the Content-Type of a JsonResponse is automatically application/json, no need to set it.

Wordpress plugin WP_error

I installed ISMS Plugin into my wordpress in order to try out the SMS service through Wordpress. However an error appeared when I click on the iSMS setting on the plugin menu.
Here is the error:
**
Fatal error: Cannot use object of type WP_Error as array in C:\wamp\www\wordpress\wp-content\plugins\isms\isms-model.php on line 17**
and here's the code for line 17:
$result = $response[body];
here is the full code for isms-model.php
<?php
class Mobiweb_ISMS_Model {
// iSMS API
protected static $api_balance = 'https://www.isms.com.my/isms_balance.php';
protected static $api_send = 'https://www.isms.com.my/isms_send.php';
public static function get_balance() {
$username = get_option('setting_username');
$password = get_option('setting_password');
$link = self::$api_balance.'?';
$link .= "un=".urlencode($username);
$link .= "&pwd=".urlencode($password);
$response = wp_remote_get($link);
$result = $response[body];
$balance = (float)$result;
if ($balance < 0) return substr($result, 8);
else return $result;
}
public static function send_isms($destination, $message, $messageType, $senderID = '') {
$username = get_option('setting_username');
$password = get_option('setting_password');
$link = self::$api_send.'?';
$link .= "un=".urlencode($username);
$link .= "&pwd=".urlencode($password);
$link .= "&dstno=".urlencode($destination);
$link .= "&msg=".urlencode($message);
$link .= "&type=".urlencode($messageType);
$link .= "&sendid=".urlencode($senderID);
$response = wp_remote_get($link);
try {
$result = $response[body];
$resultValue = (float)$result;
if ($resultValue < 0) {
return array(
'code'=>$resultValue,
'message'=>substr($result, 8)
);
} else {
return array(
'code'=>'2000',
'message'=>$result
);
}
} catch (Exception $e) {
$message = $e->getMessage();
return array(
'code'=>'-9999',
'message'=>$message
);
}
}
}
?>
What should I do to fix it? Any advise?
This plugin is badly written.
wp_remote_get() returns a WP_Error object when there's an error. Therefore, at least for debugging it and seeing what the error is, I would suggest you change it from:
$response = wp_remote_get($link);
$result = $response[body];
to
$response = wp_remote_get($link);
if (is_wp_error($response)) {
die($response->get_error_message());
}
$result = $response['body'];

Symfony2 outputting pdf using FPDF

How do I return a response in Symfony to output a pdf? I'm currently using FPDF as I don't want to use any bundles. Here is my controller action:
public function pdfAction(Request $request) {
//grab from database
$pdf = new \FPDF;
for($i = 0; $i < count($entities); $i++) {
//manipulate data
$pdf->AddPage();
$pdf->SetFont("Helvetica","","14");
$pdf->SetTextColor(255, 255, 255);
}
$pdf->Output();
return new Response($pdf, 200, array(
'Content-Type' => 'pdf'));
}
With this all I'm getting is a page with gibberish characters. I'm quite new to I/O manipulations so any help would be great. Thank you..
You need to set proper Content-Type of your response. Also, don't send your FPDF object as a content of your response, but rather the PDF output. Try this:
public function pdfAction(Request $request) {
//................//
return new Response($pdf->Output(), 200, array(
'Content-Type' => 'application/pdf'));
}
UPDATE:
To get your generated PDF file downloaded instead of displayed, you need to set disposition to attachment:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
public function pdfAction(Request $request) {
//................//
$response = new Response(
$pdf->Output(),
Response::HTTP_OK,
array('content-type' => 'application/pdf')
);
$d = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'foo.pdf'
);
$response->headers->set('Content-Disposition', $d);
return $response;
}
http://symfony.com/doc/current/components/http_foundation/introduction.html#serving-files
In symfony 2.7, I'm having a "Corrupted content" while trying to set the Content-Disposition. My fix is:
public function pdfAction(Request $request) {
//................//
$response = new Response(
$pdf->Output(),
Response::HTTP_OK,
array('content-type' => 'application/pdf')
);
return $response;
}

Resources