eajaxupload in yii failes - upload

I try ti user eajaxupload extention in yii(using this article: http://www.yiiframework.com/extension/eajaxupload
I want Upload and attache image to one of controller,
I try this code:
in controller: *(my controller name is : article)*
public function actionUpload()
{
Yii::import("ext.EAjaxUpload.qqFileUploader");
$folder= Yii::app()->baseUrl .'/uploads';// folder for uploaded files
$allowedExtensions = array("jpg");//array("jpg","jpeg","gif","exe","mov" and etc...
$sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload($folder);
$result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);
$fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
$fileName=$result['filename'];//GETTING FILE NAME
//echo $result;// it's array
}
and in _form.php (for controller) i have:
$this->widget('ext.EAjaxUpload.EAjaxUpload',
array(
'id'=>'uploadFile',
'config'=>array(
'action'=>'/article/upload',
'allowedExtensions'=>array("jpg"),//array("jpg","jpeg","gif","exe","mov" and etc...
'sizeLimit'=>10*1024*1024,// maximum file size in bytes
//'minSizeLimit'=>10*1024*1024,// minimum file size in bytes
//'onComplete'=>"js:function(id, fileName, responseJSON){ alert(fileName); }",
'showMessage'=>"js:function(message){ alert(message); }"
)
)); ?>
upload folder have full access for all!,
but when i push upload file and select a file always get error: filename, filesize and Faild!
What is wrong in my code?

What do you see on the console when you you add this
echo "<pre>";
print_r($result);
echo "</pre>";exit(0);
after $result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);

Make sure your upload folder exists. Yii::app()->baseUrl returns '...yourproject/protected'.
I use:$folder=Yii::app() -> getBasePath() . "/../images/";
Also check your console in browser(press F12). If you got 403 error, then add rules to your controller for upload action
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','upload'),
'users'=>array('*'),
),
.....

Related

How to attach a created file to mail mvc

As each user runs through my application I hold their data and dump it into a report as follows, which at the end is created into a pdf document and is later automatically downloaded on the users side(client-side). I now want to attach this document to an email and have it forwarded to them. This is where I have troubles with the attachment.
Code as follows:
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Reports/PP_RentalAgreement.rpt")));
rd.SetParameterValue("rent_agree_no", _1);
rd.SetParameterValue("r_initial", _2);
rd.SetParameterValue("r_f_name", _3);
rd.SetParameterValue("r_l_name", _4);
rd.SetParameterValue("r_id_no", _5);
rd.SetParameterValue("r_lic_no", _6);
rd.SetParameterValue("r_tel", _7);
rd.SetParameterValue("r_cell", _8);
rd.SetParameterValue("r_fax", _9);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream st = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
st.Seek(0, SeekOrigin.Begin);
if (ModelState.IsValid)
{
var m_message = new MailMessage();
m_message.To.Add(new MailAddress("JoeSoap#TextMail.com"));
m_message.Subject = "Pink Panther - Invoice";
m_message.Attachments.Add(new Attachment(st, "application/pdf", "Invoice.pdf"));
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(m_message);
return RedirectToAction("Index");
}
}
I am getting an error on this line : m_message.Attachments.Add(new Attachment(st, "application/pdf", "Invoice.pdf")); saying The specified content type is invalid.
Someone suggested to me that I should specify a path however I am not actually saving this file anywhere
How am I able to allow the file to be attached and send it to the recipient?
The System.Net.Mail.Attachment class constructor with 3 overloads consist of these parameters:
public Attachment(System.IO.Stream contentStream, string name, string mediaType)
Hence, you're assigning name and content type in reversed order, which causing invalid content type problem at this code:
m_message.Attachments.Add(new Attachment(st, "application/pdf", "Invoice.pdf"));
The correct way is putting the file name as second argument like example below:
m_message.Attachments.Add(new Attachment(st, "Invoice.pdf", "application/pdf"));
Or using MediaTypeNames for content type setting:
m_message.Attachments.Add(new Attachment(st, "Invoice.pdf", MediaTypeNames.Application.Pdf));

file URL on s3 to match files on website hosted elsewhere

First I apologize if this is a duplicate because I've looked everywhere and the answers are either for slightly different scenarios or I just can't get them to work.
My scenario:
Hosting a Drupal site on a platform that does not support files larger than 250mb. Client wants a zip file that is 500mb to be hosted on the site and the reasoning is so that the url to the file is the same as any other file on the site. They want the ability to easily remove the file and replace it with a new large file in the future.
UPDATE:
I was successful masking an s3 file url with CNAME for a subdomain, but that will not resolve the issue that it is a slightly different URL and would require it's own ssl cert.
I'm using the s3fs module to set the default file location for the site to the s3 bucket. Now while setting up a file manager module, elfinder, I can't get it to know the new location to manage the files. Elfinder assumes they are in the local default files location. Once I've resolved this, I can tackle the cname.
This is not a complete answer, just a bit of code i cannot put inside the comment.
This code generates temporary link to download private files, that stored on S3 bucket.
Use it like this:
$url = el_s3_getTemporaryLink('myaccesskey','mysecretkey','mybucket','linux.png', 1);// this link is alive for one minute.
Which will output something like: https://mybucket.s3.amazonaws.com/?sometoken
You can put that inside links like:
l('Download now', $url, ['external'=>true]);
<?php
if(!function_exists('el_crypto_hmacSHA1')){
/**
* Calculate the HMAC SHA1 hash of a string.
*
* #param string $key The key to hash against
* #param string $data The data to hash
* #param int $blocksize Optional blocksize
* #return string HMAC SHA1
*/
function el_crypto_hmacSHA1($key, $data, $blocksize = 64) {
if (strlen($key) > $blocksize) $key = pack('H*', sha1($key));
$key = str_pad($key, $blocksize, chr(0x00));
$ipad = str_repeat(chr(0x36), $blocksize);
$opad = str_repeat(chr(0x5c), $blocksize);
$hmac = pack( 'H*', sha1(
($key ^ $opad) . pack( 'H*', sha1(
($key ^ $ipad) . $data
))
));
return base64_encode($hmac);
}
}
if(!function_exists('el_s3_getTemporaryLink')){
/**
* Create temporary URLs to your protected Amazon S3 files.
*
* #param string $accessKey Your Amazon S3 access key
* #param string $secretKey Your Amazon S3 secret key
* #param string $bucket The bucket (bucket.s3.amazonaws.com)
* #param string $path The target file path
* #param int $expires In minutes
* #return string Temporary Amazon S3 URL
* #see http://awsdocs.s3.amazonaws.com/S3/20060301/s3-dg-20060301.pdf
*/
function el_s3_getTemporaryLink($accessKey, $secretKey, $bucket, $path, $expires = 5) {
// Calculate expiry time
$expires = time() + intval(floatval($expires) * 60);
// Fix the path; encode and sanitize
$path = str_replace('%2F', '/', rawurlencode($path = ltrim($path, '/')));
// Path for signature starts with the bucket
$signpath = '/'. $bucket .'/'. $path;
// S3 friendly string to sign
$signsz = implode("\n", $pieces = array('GET', null, null, $expires, $signpath));
// Calculate the hash
$signature = el_crypto_hmacSHA1($secretKey, $signsz);
// Glue the URL ...
$url = sprintf('http://%s.s3.amazonaws.com/%s', $bucket, $path);
// ... to the query string ...
$qs = http_build_query($pieces = array(
'AWSAccessKeyId' => $accessKey,
'Expires' => $expires,
'Signature' => $signature,
));
// ... and return the URL!
return $url.'?'.$qs;
}
}

How to load CSS file from profile directory (how to create URI from filepath)

My extension has saved a CSS file to the user's profile directory. Now, I want to load this CSS file into a window.
sheetsheet/utils seems to have a loadSheet(window, uri, type) method for this (https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/stylesheet_utils) but I can't figure out how to convert my CSS file path into a URI object that is expected.
My code is something like this:
const ssutils = require("sdk/stylesheet/utils"),
windows = require("sdk/windows");
var path_to_file = "c:\users\myname\appdata\local\temp\tmppr9imy.mozrunner\myextension\mycssfile.css"
for (let wind of windows.browserWindows) {
// What is the magic function I need to use?
ssutils.loadSheet(wind, someMagicFunctionHere(path_to_file), "user");
}
The sdk/url module prvcides the function you ask.
const { fromFilename } = require("sdk/url");
...
ssutils.loadSheet(wind, fromFilename(path_to_file), "user");
fromFilename converts a path to a file: URI

TCPDF and database: conflicts in PHP

Hi this my php code :
<?php require_once('tcpdf/config/lang/eng.php'); ?>
<?php require_once('tcpdf/tcpdf.php'); ?>
<?php include_once("class/class_productos.php"); ?>
<?php include_once("class/class_clientes.php"); ?>
<?php include_once("class/class_img_gen.php"); ?>
<?php include_once("class/class_acros.php"); ?> // here is MY DB CONNECTION
<?php
class MYPDF extends TCPDF {
//Page header
public function Header() {
$auto_page_break = $this->AutoPageBreak;
$this->SetAutoPageBreak(false, 0);
$img_file = 'img/pdf_fondo.jpg';
$this->Image($img_file, $x=0, $y=0, $w=210, $h=297, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0);
$this->SetAutoPageBreak($auto_page_break);
}
}
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator('ACROS');
$pdf->SetAuthor('ACROS');
$pdf->SetTitle('Lista de producto');
$pdf->SetSubject('Lista de producto');
$pdf->SetKeywords('ACROS, acros, mayorista, informática');
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(false);
$pdf->SetMargins(0, 0, 0);
$pdf->SetAutoPageBreak(FALSE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->setLanguageArray($l);
$pdf->AddPage();
$category = $_GET['c'];
$getCategory = "SELECT * FROM prod_detalle WHERE fk_marca = '$category'";
$getCategory = mysql_query($getCategory);
$count = mysql_num_rows($getCategory);
$txt = "result ".$count;
// output the HTML content
$pdf->writeHTML($txt, true, 0, true, 0);
$pdf->SetY(-30);
$pdf->SetX(0.65);
$pdf->MultiCell(20, 0, $txtB, $border = 0,$align = 'L',$fill = 0,$ln = 1,$x = '',$y = '',$reseth = false, $stretch = 0, $ishtml = true, $autopadding = false, $maxh = 0);
$pdf->Output('lista.pdf', 'I');
?>
and i'm getting this two warnings :
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean
given in /mnt/futurehome/netlogiq/public_html/acros/lista_pdf.php on
line 64
Warning: Cannot modify header information - headers already sent by
(output started at
/mnt/futurehome/netlogiq/public_html/acros/lista_pdf.php:64) in
/mnt/futurehome/netlogiq/public_html/acros/tcpdf/tcpdf.php on line
5405 TCPDF ERROR: Some data has already been output to browser, can't
send PDF file
Can anyone help me with this ?? If run the query in phpmyadmin, it returns the wanted data. So the query works fine !
The reason you are getting the error from mysql_num_rows() is because you haven't initialized the connection to the database. You are also using the old (and deprecated as og PHP 5.5) MySQL interface - you should look into using mysqli or PDO instead.
A full explanation of how to initialize the connection to the database and communicate with it using the correct resource handle is, IMO, beyond the scope of an SO answer. Maybe start here instead:
http://www.php.net/manual/en/mysqli.quickstart.connections.php
The reason you're getting the second error is simply because the first error message is being sent to the browser before your call to $pdf->Output(). Once you get your database connection working and remove the error messages that problem will go away.
Just remove the line
require_once('tcpdf/config/lang/eng.php');
and
edit the tcpdf.php file from the tcpdf folder:
add the line ob_end_clean(); as below (3rd last line):
public function Output($name='doc.pdf', $dest='I') {
//LOTS OF CODE HERE....}
switch($dest) {
case 'I': {
// Send PDF to the standard output
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
//some code here....}
case 'D': { // download PDF as file
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
break;}
case 'F':
case 'FI':
case 'FD': {
// save PDF to a local file
//LOTS OF CODE HERE..... break;}
case 'E': {
// return PDF as base64 mime email attachment)
case 'S': {
// returns PDF as a string
return $this->getBuffer();
}
default: {
$this->Error('Incorrect output destination: '.$dest);
}
}
ob_end_clean(); //add this line here
return '';
}

Symfony Batch Action

I'm trying to create a batch action (symfony admin) that enables the creation/download on the fly of zip file containing users photos which are avaialable on the uploads/images directory.
Here is the code that I already implemented:
public function executeBatchDownloadFotos(sfWebRequest $request)
{
$zip = new ZipArchive();
// atheletes identifiers
$ids = $request->getParameter('ids');
// get all the atheletes objects
$q = Doctrine_Query::create()
->from('Atleta a')
->whereIn('a.id', $ids);
foreach ($q->execute() as $atleta)
{
$zip->addFile($atleta->id . '_' . $atleta->Clube . '.jpg', 'uploads/atletas/' . $atleta->id . '_' . $atleta->Clube . '.jpg');
}
}
By the other hand, here is the view configuration:
BatchDownloadFotos:
http_metas:
content-type: application/zip
has_layout: false
For some reason, each time execute the batch action, the browser do not prompts me with the window to download the zip file.
After you create ZIP archive in your controller file you should send the content to the browser.
You can do this using methods described here: http://www.symfony-project.org/gentle-introduction/1_4/en/06-Inside-the-Controller-Layer#chapter_06_sub_action_termination
Now you are trying to create ZIP file, but you are not sending it to the browser. You should use setContent() and setHttpHeader() methods.
Your action could look like this (you should add error handling):
public function executeIndex(sfWebRequest $request)
{
$fileName = '/tmp/test.zip';
$zip = new ZipArchive();
$zip->open($fileName, ZipArchive::CREATE);
// add some files to archive
$zip->addFile('/tmp/test', 'test.txt');
$zip->close();
$this->getResponse()->setContent(file_get_contents($fileName));
$this->getResponse()->setHttpHeader('Content-Type', 'application/zip');
$this->getResponse()->setHttpHeader('Content-Disposition',
'attachment; filename=download.zip');
return sfView::NONE;
}

Resources