Image not moving to proper folder zend framework2 - php

I started working on Zend Framework image upload.The code is not showing any errors but image not moving to proper destination.
public function uploadAction()
{
error_reporting(E_ALL);
ini_set('display_errors', 1);
$form = new UploadForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload'); //upload destination
$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if($favadapter->receive($favicon))
{
echo "suceess";
}
else
{
echo "Failed";
}
die;
}
}
return array('form' => $form);
}
The image is not received and gives failed message.Can you solve this problem.Thanks in advance

You write "gives failed message" so apparently something goes wrong. You should try to find out what and why... All we can do is guess with the information you are giving inside your question.
If you read the ZF2 documentation on this file adapter class here then you can see that the adaper has a getMessages method. This might give you some insight on what actually goes wrong:
$adapter = new Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
This code snippet comes straight out of the official docs!

Your final running code make sure you comment filters
public function uploadAction()
{
error_reporting(0);
$em = $this->getEntityManager();
$form = new UploadForm($em);
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload/'); //upload destination
//$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if (!$favadapter->receive())
{
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
else
{
echo "success";
}
// die;
}
}
// if ($request->isPost())
// {
// $fname = $_FILES['fileupload']['name'];
// $tmp_name = $_FILES["fileupload"]["tmp_name"];
// $uploads_dir = 'public/img/upload';
// if(move_uploaded_file($tmp_name,"$uploads_dir/$fname"))
// {
// echo "Uploaded";
// }
// else
// {
// echo "Error";
// }
// }
return array('form' => $form);
}

Related

File not found at path: on laravel 5.6

i am using laravel 5.6, i will try to make function multiple upload video, and get frame and duration with laravel-ffmpeg, but when i try to upload one video for example, always show error like "File not found at path:",
this is my function to store video and get duration & frame :
public function doCreate($lessonsid)
{
if (empty(Session::get('contribID'))) {
return redirect('contributor/login');
}
# code...
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'judul' => 'required',
// 'video.*' => 'mimes:mp4,mov,ogg,webm |required|max:100000',
// 'image.*' => 'mimes:jpeg,jpg,png,gif|required|max:30000'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
} else {
$now = new DateTime();
$cid = Session::get('contribID');
$title = Input::get('judul');
$image_video = Input::file('image');
$lessons_video = Input::file('video');
// dd($lessons_video);
// $media = FFMpeg::open('https:/dev.cilsy.id/assets/source/lessons/lessons-74/video-8/1. Introduction (2).mp4');
// $frame = $media->getFrameFromString('00:00:13.37');
// dd($media);
$description = Input::get('desc');
$video=Video::where('lessons_id',$lessonsid)->get();
$count_video=count($video);
if (!is_dir("assets/source/lessons/lessons-$lessonsid")) {
$newforder=mkdir("assets/source/lessons/lessons-".$lessonsid);
}
$i=$count_video + 1;
foreach ($title as $key => $titles) {
$type_video =$lessons_video[$key]->getMimeType();
if (!is_dir("assets/source/lessons/lessons-".$lessonsid."/video-".$i)) {
$newforder=mkdir("assets/source/lessons/lessons-".$lessonsid."/video-".$i);
}
$DestinationPath= 'assets/source/lessons/lessons-'.$lessonsid.'/video-'.$i;
//insert image
if(!empty($image_video[$key])){
$imagefilename = $image_video[$key]->getClientOriginalName();
$image_video[$key]->move($DestinationPath, $imagefilename);
}else{
$imagefilename = '';
}
if($imagefilename ==''){
$url_image= $imagefilename;
}else{
$urls=url('');
$url_image= $urls.'/assets/source/lessons/video-'.$i.'/'.$imagefilename;
}
//insert video
if(!empty($lessons_video[$key])){
$lessonsfilename = $lessons_video[$key]->getClientOriginalName();
$lessons_video[$key]->storeAs($DestinationPath, $lessonsfilename);
}else{
$lessonsfilename = '';
}
if($lessonsfilename ==''){
$url_video= $lessonsfilename;
}else{
$urls=url('');
$url_video= $urls.'/assets/source/lessons/video-'.$i.'/'.$lessonsfilename;
}
$store = new Video;
$store->lessons_id = $lessonsid;
$store->title = $titles;
$store->image = $url_image;
$store->video = $url_video;
$store->description = $description[$key];
$store->type_video = $type_video;
$store->durasi = 0;
$store->created_at = $now;
$store->enable=1;
$store->save();
if($store){
$media = FFMpeg::open($url_video);
// $frame = FFMpeg::open($link)
// ->getFrameFromSeconds(10)
// ->export()
// ->toDisk('public')
// ->save($filename.'.png');
dd($media);
$durationInSeconds = $media->getDurationInSeconds();
// dd($media);
}
$i++;
}
// Session::set('lessons_title',$title);
// Session::set('lessons_category_id',$category_id);
// Session::set('lessons_image',$image);
// Session::set('lessons_description',$description);
return redirect('contributor/lessons/'.$lessonsid.'/view')->with('success','Penambahan video berhasil');
}
}
this is message error, when i try to upload my video
anyone can help me?
try with public_path()
$DestinationPath= public_path().'/'.'assets/source/lessons/lessons-'.$lessonsid.'/video-'.$i;
You files are not saving, you should use public_path helper for storing and retrieving files back.
$image_video[$key]->move(public_path('lessons/lessons-'.$lessonsid.'/video-'.$i), $imagefilename);
Or you can store them into storage folder
$image_video[$key]->move(storage_path('lessons/lessons-'.$lessonsid.'/video-'.$i), $imagefilename);
You can retrieve back files using these helpers.
Hope this helps.

Laravel : Update field when value is exist

I have some problem with updating file. I have a form with the following attributes :
title
text
pdf file
The problem is the update operation will save the pdf file as the following value :
with file : ["example.pdf"]
no file : [""]
It will include [""] to the pdf file value when updated.
I want the pdf file updated to a new file when a new file is selected, old file remained when there is no new file selected and null value to file when there is no file, to begin with.
Here is the update controller.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if ($getFile) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
$old = Announcement::where('id',$main_id)->pluck('brochure');
if (empty($old)) {
$announcements->brochure = null;
}
else {
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
What am I doing wrong in this code? Please help me. Thank you.
Change this:
$old = Announcement::where('id',$main_id)->pluck('brochure');
To:
$old = Announcement::where('id',$main_id)->value('brochure');
The thing is pluck() will return a collection of brochure, not a string. And value() will return a string or null.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if (!empty(Input::file('new_brochure'))) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
else
$old = Announcement::where('id',$main_id)->value('brochure');
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}

Inserting uploaded filenames into database table

I am trying to insert uploaded filenames to a table with the date they were uploaded, but I am running into some errors with trying to get the values of the filename with $_FILES
Here is my code:
public function uploadAction()
{
if (!$user = $this->identity()) {
return $this->redirect()->toUrl('/login/log');
}
$user = $this->identity();
$layout = $this->layout();
$layout->setVariable('user1', $user->username);
$form = new FileUploadForm();
$request = $this->getRequest();
if ($request->isPost()) {
$file = new File();
$form->setInputFilter($file->getInputFilter());
$captions = $request->getPost()->toArray();
$get_file = $this->params()->fromFiles('file');
$data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min' => '10kB', 'max' => FileHandler::FILESIZE . 'MB'));
$extension = new Extension(array('jpg', 'jpeg', 'png'), true);
$adapter = new Http();
$adapter->setValidators(array($size, $extension), $get_file['name']);
if (!$adapter->isValid()) {
return $this->redirect()->toUrl('/admin/upload-failure');
} else {
$dir_check = !is_dir(FileHandler::UPLOAD_PATH . $user->username)
?
mkdir(FileHandler::UPLOAD_PATH . $user->username) ? FileHandler::UPLOAD_PATH . $user->username : null
: FileHandler::UPLOAD_PATH . $user->username;
$adapter->setDestination($dir_check);
if ($adapter->receive($get_file['name'])) {
$this->getFileUploadFactory()->insertUploadDate($_FILES);
$file->exchangeArray($form->getData());
return $this->redirect()->toUrl('/admin/upload-success');
} else {
return $this->redirect()->toUrl('/admin/upload-failure');
}
}
}
}
public function insertUploadDate(array $file)
{
try {
$insert = new Insert('uploads');
foreach ($file as $key => $value) {
$insert->columns(array('filename', 'upload_date'))
->values(array('filename' => $value, 'upload_date' => date('Y-m-d')));
$adapter = $this->table_gateway->getAdapter();
$adapter->query(
$this->sql->getSqlStringForSqlObject($insert),
$adapter::QUERY_MODE_EXECUTE
);
}
return true;
} catch (\PDOException $e) {
// save the exception message to the error file
$writer = new Stream(self::ERROR_PATH);
$logger = new Logger();
$logger->addWriter($writer);
$logger->info($e->getMessage() . "\r\r");
return false;
}
}
and then in the controller I am calling it like this:
$this->getFileUploadFactory()->insertUploadDate($_FILES);
Like I said, it's not inserting the correct names of the files I uploaded (using html5 multiple upload option)
Thanks!

ZF2 Image Upload Warning "Creating default object from empty value"

I am having a issue on image upload in Zend Framework 2, where when i submit the form with image it give a "Creating default object from empty value" warning and file does not save in the folder.
If I submit the form with empty filed for images and upload then the content will save in the DB.
I have add my codes for reference
public function addAction(){
$form = new Add();
$brand = new Brand();
$form->bind($brand);
$request = $this->getRequest();
if ($request->isPost()) {
$post = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$adapter = new \Zend\File\Transfer\Adapter\Http();
$files = $adapter->getFileInfo();
$mediaFileHttpPostName = 'image-file';
$imageFile = $files[$mediaFileHttpPostName];
$adapter->setDestination('./public/media');
$adapter->addValidator('Extension', false, array('jpge'), $mediaFileHttpPostName);
$adapter->addFilter('Rename',
array(
'target'=> './public/media/'.$imageFile['name'],
'overwrite'=>true),
$mediaFileHttpPostName);
if(!empty($imageFile['name'])){
if (!$adapter->isValid()){
$returnObject->errorMessage = $adapter->getMessages();
$returnObject->result = 0;
} else {
try {
$adapter->receive($mediaFileHttpPostName);
$returnObject->result = 1;
} catch (\Zend\Filter\Exception\InvalidArgumentException $e) {
$returnObject->errorMessage = $e->getMessage();
$returnObject->result = 0;
}
}
}
$form->setData($post );
if ($form->isValid()) {
$recordlist = $this->getServiceLocator()->get('BrandService')->insert($brand,'',$form->getHydrator());
$this->flashMessenger()->addMessage('New brand added!');
return $this->redirect()->toRoute('zfcadmin/shop/brands');
}
}
You are not declaring $returnObject.
You should do:
....
if ($request->isPost()) {
$returnObject= new stdClass();
...

Codeigniter 2.1 controller not found

I have conroller baner, and when I try to run it (run upload function http://localhost/010/baner/upload_img), I got 404 error:
The page you requested was not found
What is wrong here?
The controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Upload_Baner extends CI_Controller {
protected $path_img_upload_folder;
protected $path_img_thumb_upload_folder;
protected $path_url_img_upload_folder;
protected $path_url_img_thumb_upload_folder;
protected $delete_img_url;
function __construct() {
parent::__construct();
$this->setPath_img_upload_folder("public/img/promotions/");
$this->setPath_img_thumb_upload_folder("public/img/promotions/thumbnails/");
$this->setDelete_img_url(base_url() . 'upload_baner/deleteImage/');
$this->setPath_url_img_upload_folder(base_url() . "public/img/promotions/");
$this->setPath_url_img_thumb_upload_folder(base_url() . "public/img/promotions/thumbnails/");
}
public function upload_img() {
//Format the name
$name = $_FILES['userfile']['name'];
$name = strtr($name, 'ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃà áâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
// replace characters other than letters, numbers and . by _
$name = preg_replace('/([^.a-z0-9]+)/i', '_', $name);
//Your upload directory, see CI user guide
$config['upload_path'] = $this->getPath_img_upload_folder();
$config['allowed_types'] = 'gif|jpg|png|JPG|GIF|PNG';
$config['max_size'] = '1000';
$config['file_name'] = $name;
//Load the upload library
$this->load->library('upload', $config);
if ($this->do_upload()) {
//If you want to resize
$config['new_image'] = $this->getPath_img_thumb_upload_folder();
$config['image_library'] = 'gd2';
$config['source_image'] = $this->getPath_img_upload_folder() . $name;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 193;
$config['height'] = 94;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data = $this->upload->data();
//Get info
$info = new stdClass();
$info->name = $name;
$info->size = $data['file_size'];
$info->type = $data['file_type'];
$info->url = $this->getPath_img_upload_folder() . $name;
$info->thumbnail_url = $this->getPath_img_thumb_upload_folder() . $name; //I set this to original file since I did not create thumbs. change to thumbnail directory if you do = $upload_path_url .'/thumbs' .$name
$info->delete_url = $this->getDelete_img_url() . $name;
$info->delete_type = 'DELETE';
//Return JSON data
if (IS_AJAX) { //this is why we put this in the constants to pass only json data
echo json_encode(array($info));
//this has to be the only the only data returned or you will get an error.
//if you don't give this a json array it will give you a Empty file upload result error
//it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
} else { // so that this will still work if javascript is not enabled
$file_data['upload_data'] = $this->upload->data();
echo json_encode(array($info));
}
} else {
// the display_errors() function wraps error messages in <p> by default and these html chars don't parse in
// default view on the forum so either set them to blank, or decide how you want them to display. null is passed.
$error = array('error' => $this->upload->display_errors('',''));
echo json_encode(array($error));
}
}
public function do_upload() {
if (!$this->upload->do_upload()) {
return false;
} else {
//$data = array('upload_data' => $this->upload->data());
return true;
}
}
//Function Delete image
public function deleteImage() {
//Get the name in the url
$file = $this->uri->segment(3);
$success = unlink($this->getPath_img_upload_folder() . $file);
$success_th = unlink($this->getPath_img_thumb_upload_folder() . $file);
//info to see if it is doing what it is supposed to
$info = new stdClass();
$info->sucess = $success;
$info->path = $this->getPath_url_img_upload_folder() . $file;
$info->file = is_file($this->getPath_img_upload_folder() . $file);
if (IS_AJAX) {//I don't think it matters if this is set but good for error checking in the console/firebug
echo json_encode(array($info));
} else { //here you will need to decide what you want to show for a successful delete
var_dump($file);
}
}
public function get_files() {
$this->get_scan_files();
}
public function get_scan_files() {
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name) {
$info = $this->get_file_object($file_name);
} else {
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
}
protected function get_file_object($file_name) {
$file_path = $this->getPath_img_upload_folder() . $file_name;
if (is_file($file_path) && $file_name[0] !== '.') {
$file = new stdClass();
$file->name = $file_name;
$file->size = filesize($file_path);
$file->url = $this->getPath_url_img_upload_folder() . rawurlencode($file->name);
$file->thumbnail_url = $this->getPath_url_img_thumb_upload_folder() . rawurlencode($file->name);
//File name in the url to delete
$file->delete_url = $this->getDelete_img_url() . rawurlencode($file->name);
$file->delete_type = 'DELETE';
return $file;
}
return null;
}
protected function get_file_objects() {
return array_values(array_filter(array_map(
array($this, 'get_file_object'), scandir($this->getPath_img_upload_folder())
)));
}
public function getPath_img_upload_folder() {
return $this->path_img_upload_folder;
}
public function setPath_img_upload_folder($path_img_upload_folder) {
$this->path_img_upload_folder = $path_img_upload_folder;
}
public function getPath_img_thumb_upload_folder() {
return $this->path_img_thumb_upload_folder;
}
public function setPath_img_thumb_upload_folder($path_img_thumb_upload_folder) {
$this->path_img_thumb_upload_folder = $path_img_thumb_upload_folder;
}
public function getPath_url_img_upload_folder() {
return $this->path_url_img_upload_folder;
}
public function setPath_url_img_upload_folder($path_url_img_upload_folder) {
$this->path_url_img_upload_folder = $path_url_img_upload_folder;
}
public function getPath_url_img_thumb_upload_folder() {
return $this->path_url_img_thumb_upload_folder;
}
public function setPath_url_img_thumb_upload_folder($path_url_img_thumb_upload_folder) {
$this->path_url_img_thumb_upload_folder = $path_url_img_thumb_upload_folder;
}
public function getDelete_img_url() {
return $this->delete_img_url;
}
public function setDelete_img_url($delete_img_url) {
$this->delete_img_url = $delete_img_url;
}
}
Your controller is named Upload_Baner so unless you have a route defined that maps baner to upload_Baner this won't work. Does this url work?:
http://localhost/010/upload_Baner/upload_img
That is what your current controller will map to without the route.

Categories