Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

unable to get a file uploaded, need help.

Unable to get the file upload working, the below is my controller action.

 public function applyJobAction($id)
    {
        $form = new ApplyJobForm();

        if ($this->request->isPost()) {

            if ($form->isValid($this->request->getPost()) == false && $this->request->hasFiles() == true) {
                foreach ($form->getMessages() as $message) {
                    $this->flash->error($message);
                }
            } else {
                $job = Jobs::findFirstById($id);
                if (!$job) {
                    $this->flash->danger('There is no such job');
                } else {
                    $applyJob = new ApplyJobs();
                    $applyJob->name = $this->request->getPost('name', 'striptags');
                    $applyJob->email = $this->request->getPost('email', 'email');
                    $applyJob->message = $this->request->getPost('message', 'striptags');

                    foreach ($this->request->getUploadedFiles() as $file)
                    $file->moveTo('files/' . $file->getName());

                    $applyJob->file_name = $file->getName();
                    $applyJob->jobId = $job->id;
                    $applyJob->created = date('Y-m-d');

                    if ($applyJob->save()) {
                        $this->flash->success('Success! You have successfully applied for this job');
                    } else {
                        foreach ($applyJob->getMessages() as $message) {
                            $this->flash->error($message);
                        }
                    }
                }
            }
        }

        $this->view->form = new ApplyJobForm($applyJob, array(
            'apply' => true
        ));

    }

In my volt template I am using this to render the file upload element.

{{ form.render("upload") }}

and in my form i have defined the below element like this.

        $upload = new File('upload', array(
            'placeholder' => 'upload',
        ));

        $upload->addValidators(array(
            new PresenceOf(array(
                'message' => 'We didn\'t see any attachments Please attach the file and try again'
            ))           
        ));

        $this->add($upload);

If I am dumping $_Files global array I am seeing that my form has sent the file along with request. Please advise.

edited Nov '15

Hey, can you check the example from phalcon docs here:

https://docs.phalconphp.com/en/latest/api/Phalcon%5Http%5Request%5File.html

Also read the methods below;



64.2k
$file = new \Phalcon\Http\Request\File($_FILES[$upload]);

i dont see where $upload variable is defined ?

edited Nov '15

Yeap check @Izopi4a suggestion as well.

Also i would strongly recommend to check what kind of file user is uploading. In your code the user can upload anything and cause you troubles. Phalcon provides function so you can get the mimetype of the uploaded file:

public getRealType ()

Sample code would look like:

// Images mimetypes
$allowedFileFormats = array(
    'image/x-icon' => 'ico',
    'image/jpeg' => 'jpg',
    'image/vnd.adobe.photoshop' => 'psd',
    'image/png' => 'png',
    'image/gif' => 'gif',
    'image/bmp' => 'bmp',
);

// Check allowed formats
if (array_key_exists($file->getRealType(), $allowedFileFormats)) { 
    // allowed
} else {
    // not allowed
}

Also, here is a good list of popular if not all mimetypes: http://www.freeformatter.com/mime-types-list.html

edited Nov '15

I have modified the controller as per the example, but I am still getting error, the error from my form is thrown back saying We didn\'t see any attachments Please attach the file and try again I have updated my code in my first post.



64.2k

but is the file uploaded correctly ?

No, the file is not uploaded.

but is the file uploaded correctly ?



64.2k
edited Nov '15

bases on this https://github.com/phalcon/cphalcon/blob/c8d4916bbfd0cb18395fe25d8c5a663fc5077d8f/phalcon/http/request/file.zep#L178

can you try with full path ?

like:

   $file->moveTo('/var/www/myapp/public/upploads/' . $file->getName());
edited Nov '15

after adding the full path like below and removing the presenceof validator in the form it gets uploaded correctly now.

$file->moveTo('C:/xampp/htdocs/app/public/files/' . $file->getName());

@Izopi4a can you please help me in adding the validation for the file mime type. Appreciate your help.



64.2k
Accepted
answer
edited Nov '15

@nikolay-mihaylov posted good example.

more or less something like this:

// .....
$applyJob = new ApplyJobs();
$applyJob->name = $this->request->getPost('name', 'striptags');
$applyJob->email = $this->request->getPost('email', 'email');
$applyJob->message = $this->request->getPost('message', 'striptags');

// Images mimetypes
$allowedFileFormats = array(
'image/x-icon' => 'ico',
'image/jpeg' => 'jpg',
'image/vnd.adobe.photoshop' => 'psd',
'image/png' => 'png',
'image/gif' => 'gif',
'image/bmp' => 'bmp',
);

foreach ($this->request->getUploadedFiles() as $file){
if (array_key_exists($file->getRealType(), $allowedFileFormats)) {
$file->moveTo('C:/xampp/htdocs/app/public/files/' . $file->getName());
}
}

$applyJob->file_name = $file->getName();
$applyJob->jobId = $job->id;

....

about the validation.. i can write you an solution but it wont be perfect, for that reason i create records in my database with uploads, or you have to be very strict naming your files.

as simple as it can be:

$directory = "C:/xampp/htdocs/app/public/files/".$job->id . '/';
$filecount = 0;
$files = glob($directory . "*");
if ($files){
    $filecount = count($files);
}

if ($filescount == 0){
    //falshmessage bla bla bla
} else {
//continue script.
}

you have to think the process trough if you want to make a good validation. Also i always rename the files. usually

$filename = md5(time()).".".$file->getRealType();

just to be sure someone doesnt upload a chineese filename and break everything, also there wont be any blank spaces in filename which could also couse problems.

let me know what exacly you want and we can post something for you :-)

@Izopi4a thanks so much for your kind gesture. I tried with the inputs that you gave me, but its again breaking the process. The record is added to database but the file is missing from the folder. Please find my scenario below.

There is a form that accepts applications to job that its associated with, which takes four fields i.e. name, email, message and the resume (file upload) (word / pdf / docx, txt, rtf) file as the attachment and saves the same to the database. Would be of great help if you could help me on this issue.



64.2k
edited Nov '15

send me your skype on r......

@Izopi4a just sent you my details. Look forward to hear from you soon.