laravel multiple image uploader can't upload? - php

I need to upload much (for about 300-400 photos) at once. I’m using Laravel 4.2 to do so.
Everything works, except it doesn’t upload. What I have:
Controller:
edit
public function postUpload() {
// getting all of the post data
$files = array('file' => Input::file('file'));
//echo "<pre>";
//var_dump($files);
//echo "</pre>";
//die;
$map = Input::get('mapname');
// setting up rules
$rules = array('file' => 'max:10000'); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($files, $rules);
if ($validator->fails()) {
// send back to the page with the input data and errors
Session::flash('error_message', 'Er ging iets mis!');
return Redirect::to('admin/img/upload')->withInput()->withErrors($validator);
}
else {
// checking file is valid.
if(Input::hasFile('file'))
{
//echo "<pre>";
//var_dump(Input::hasFile('file'));
//echo "</pre>";
//die;
foreach($files as $file)
{
$destinationPath = 'public/pictures/overall/'.$map; // upload path
$filename = str_random(40).'_'.$file[0]->getClientOriginalName();
$extension = $file[0]->getClientOriginalExtension(); // getting image extension
$file[0]->move($destinationPath, $filename); // uploading file to given path
}
// sending back with message
Session::flash('success', 'Succesvol geüpload!');
return Redirect::to('admin/img/upload');
}
else {
// sending back with error message.
Session::flash('error_message', 'Er ging iets mis!');
return Redirect::to('admin/img/upload');
}
}
}
The view (rendered):
<form method="POST" action="http://localhost/RPR/admin/img/uploadfile" accept-charset="UTF-8" enctype="multipart/form-data">
<input name="_token" type="hidden" value="92YNpAB9HsmWJm8FbepriZWfy9mjUI2rziVBKJhs">
<select id="mapname" name="mapname">
<option value="TAC-Tielt-Shakedown-2015">TAC Tielt Shakedown 2015</option>
<option value="TAC-Tielt-2013">TAC Tielt 2013</option>
<option value="Rally-van-Staden-2015">Rally van Staden 2015</option>
</select>
<br><br>
<input multiple="multiple" name="file" type="file">
<br>
<button type="submit" class="btn btn-success">Uploaden</button>
</form>
The select is created automatically.
Could someone find the issue? It doesn’t do anything.
I did a var_dump on the post, but that only gives me the token and mapname, no image... what is kind of weird?

- List item
The issue is with the input field you are using to upload, I assume you are uploading multiple images
`<input multiple="multiple" name="file" type="file">` -- this wouldnt work, update to this:
`<input multiple="multiple" name="file[]" type="file">`
and also your controller:
$files = Input::file('file');
if ($files){
///upload logic
foreach($files as $file)
{
$destinationPath = 'public/pictures/overall/'.$map;
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
}
// sending back with message
Session::flash('success', 'Succesvol geüpload!');
return Redirect::to('admin/img/upload');
}
that should work

Related

codeigniter do_upload not working

I'm trying to add a file upload function in my website using codeigniter's upload library.
here's my view file (display.php):
<html>
<body>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="filename" />
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
</body>
</html>
and here's the controller:
public function testupload()
{
if ( ! empty($_FILES))
{
echo 'start upload';
$config['upload_path'] = './assets/img/tempfile/';
$this->load->library('upload');
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('filename'))
{
echo 'error!';
}
else
{
echo 'success!';
}
echo 'end upload';
}
$this->load->view('display', $this->data);
}
but the code seems to stop after $this->upload->initialize($config); the file was not uploaded, and there was no message at all. only the 'start upload' message appeared; the echo 'success' , echo 'error' , and echo 'end upload' do not appear.
why is that? can anyone help me??
Late from party, but maybe this can help somebody with same problem. Please try this:
Views:
<?php echo form_open_multipart('test/upload');?>
<input type="file" name="photo">
<?php echo form_close();?>
Controller:
class Test extends CI_Controller {
function upload() {
$config = array(
'upload_path' => './assets/upload/',
'allowed_types'=> 'gif|jpg|png',
'encrypt_name' => TRUE // Optional, you can add more options as need
);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('photo')) {
echo '<pre>';
print_r($this->upload->display_errors());
exit();
} else {
echo '<pre>';
print_r($this->upload->data());
exit();
}
}
}
Inside views i recomended use this function form_open_multipart('ctrl/method') but if you prefer using HTML5 forms, just be sure correct the attributes in form like this.
<form action="<?=site_url('ctrl/method')?>" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="photo">
</form>
More preferences in $config['..'] can you find in documentation CodeIgniter https://codeigniter.com/user_guide/libraries/file_uploading.html
Try like this....
public function testupload()
{
if ( ! empty($_FILES))
{
echo 'start upload';
$config['upload_path'] = './assets/img/tempfile/';
$this->load->library('upload',$config);
if ( ! $this->upload->do_upload('filename'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('display', $error); //loads the view display.php with error
}
else
{
echo 'success!';
}
echo 'end upload';
$data = array('upload_data' => $this->upload->data());
$this->load->view('display', $data); //loads view display.php with data
}
}
change from
$config['upload_path'] = './assets/img/tempfile/';
to
$config['upload_path'] = 'assets/img/tempfile/';
i check this code this work perfect
simply add this line
$config['allowed_types'] = 'png|gif|jpg|jpeg';
$config['max_size'] = '7000';
after this
$config['upload_path'] = './assets/img/tempfile/';
or you can also set this in view page
action="<?php echo base_url('YourController/testupload');?>"
this is due to php server version and it's option.
1).go to cpanel account
2).click "select php version", in the software section.
3).tap the "fileinfo" chexbox in the php option and save.
now you can upload file perfectly.
Same issue as described. I have fixed it using the following: Open the file system/libraries/Upload.php go to function validate_upload_path() and add the command return TRUE; as a last line inside this function. Save and try again.
use this for image upload:
$valid_extensions = array('jpeg', 'jpg', 'png');
if ($_FILES['filename']['error'] == 0) {
$img = $_FILES['filename']['name'];
$tmp = $_FILES['filename']['tmp_name'];
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
if (in_array($ext, $valid_extensions)) {
$path = "./assets/img/tempfile/" . strtolower($img);
if (move_uploaded_file($tmp, $path)) {
$_POST['filename'] = $path;
}
}
}
use insert query to insert file :
$this->db->insert('table_name', $_POST);
Having the same problem on macOS. It seems that if you are not the "main" user of your laptop/pc, the default permission is "Read Only". You must change it to "Read & Write".
Right click on the folder
Get Info
Sharing and permissions
Change 'Read Only' to 'Read & Write'
add allowed file type parameter in config
$config['allowed_types'] = 'gif|jpg|png';
your code is missing the following,
$this->load->library('upload',$config);
Recorrect it by rewriting the above code.

Create Dynamic fileupload api in php

I am working on file upload api in php. For Now I just create this simple php which will upload the file from an html page to server. But in this code the fileupload control's name is fixed so I pass that name in my php code for upload the file. But I want to create this api for third party. If anybody ask for api then I will give link of my api and they will consume it. Now anybody please help me to convert this into dynamic
Here is the html code
<html>
<head>
</head>
<body>
<h2>Upload Image </h2>
<form action="http://mvcangularworld.com/api.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="filename" value="" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
and here is my php code for api.php
<?php
// Path to move uploaded files
$target_path = 'images/';
$response = array();
$file_upload_url = $target_path;
$filename = $_POST['filename'];
if (isset($_FILES['filename']['name']))
{
$target_path = $target_path . basename($_FILES['filename']['name']);
// reading other post parameters
echo $_FILES['filename']['name']."<br />";
echo $_FILES['filename']['tmp_name']."<br />";
$response['file_name'] = basename($_FILES['filename']['name']);
try
{
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['filename']['tmp_name'], $target_path))
{
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}
// File successfully uploaded
//echo $file_upload_url . basename($_FILES['filename']['name']);
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['filename']['name']);
}
catch (Exception $e)
{
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
}
//else
//{
// File parameter is missing
/* $response['error'] = true;
$response['message'] = 'Not received any file';
} */
// Echo final json response to client
echo
json_encode($response, JSON_UNESCAPED_SLASHES);
?>
here is the api link
http://mvcangularworld.com/api.php
Please help me to make this api dynamic
A simple solution can be, add a hidden field which have name of file field like:
<input type="hidden" name="fileFieldName" value="filename" />
and on server side:
$fileFieldName = $_POST['fileFieldName'];
move_uploaded_file($_FILES[$fileFieldName]['tmp_name']

Error in uploading files in yii2 move_upload function

Am doing multiple file upload in the controller but the file doesn't get uploaded
controller code: for the upload
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$evidence->save();
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
I have tried var_dump($images['name'] and everything seems okay the move file does not upload the file
Check what you obtain in $_FILES and in $_POST and evaluate your logic by these result...
The PHP manual say this function return false when the filename is checked to ensure that the file designated by filename and is not a valid filename or the file can be moved for some reason.. Are you sure the filename generated is valid and/or can be mooved to destination?
this is the related php man php.net/manual/en/function.move-uploaded-file.php
Have you added enctype attribute to form tag?
For example:
<form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>

Upload in Google Chrome not working

I am creating simple file upload (for pictures). I tried in Opera and in FireFox and uploading is working fine. But when I upload via Google Chrome, picture is not uploaded. Can you please tell me where is problem:
here is php script that is used for storing picture in database
<?php
$id=$_SESSION['user_id'];
$user_id=$_SESSION['user_id'];
$album_id=$_POST['album'];
$max_size = 500; // Sets maxim size allowed for the uploaded files, in kilobytes
// sets an array with the file types allowed
$allowtype = array('bmp', 'gif', 'htm', 'html', 'jpg', 'jpeg', 'mp3', 'pdf', 'png', 'rar', 'zip');
// if the folder for upload (defined in $updir) doesn't exist, tries to create it (with CHMOD 0777)
/*if (!is_dir($updir)) mkdir($updir, 0777);*/
/** Loading the files on server **/
$result = array(); // Array to store the results and errors
// if receive a valid file from server
if (isset ($_FILES['files'])) {
// checks the files received for upload
$file_name=$_FILES['files']['name'];
$file_type=$_FILES['files']['type'];
$file_size=$_FILES['files']['size'];
$file_tmp=$_FILES['files']['tmp_name'];
for($f=0; $f<count($_FILES['files']['name']); $f++) {
$file_name = $_FILES['files']['name'][$f];
$random_name=rand();
// checks to not be an empty field (the name of the file to have more then 1 character)
if(strlen($file_name)>1) {
// checks if the file has the extension type allowed
$type=explode('.', $file_name);
$type=end($type);
if (in_array($type, $allowtype)) {
// checks if the file has the size allowed
if ($_FILES['files']['size'][$f]<=$max_size*1000) {
// If there are no errors in the copying process
if ($_FILES['files']['error'][$f]==0) {
$query = mysql_query("SELECT username from users WHERE id = '$id' ");
while($run=mysql_fetch_array($query)){
$username=$run['username'];
}
$query = mysql_query("SELECT album.name an from album WHERE album.id = '$album_id' ");
while($run=mysql_fetch_array($query)){
$album_name=$run['an'];
}
mysql_query("INSERT INTO photos VALUE ('', '$album_id', '$random_name.jpg', '$user_id')");
// Sets the path and the name for the file to be uploaded
// If the file cannot be uploaded, it returns error message
if (move_uploaded_file ($_FILES['files']['tmp_name'][$f],"./users/".$username."/".$album_name."/".$random_name.".jpg")) {
/*$result[$f] = ' The file could not be copied, try again';*/
$result[$f] = '<b>'.$file_name.'</b> - OK';
}
else {
$result[$f] = ' The file could not be copied, try again';
}
}
}
else { $result[$f] = 'The file <b>'. $file_name. '</b> exceeds the maximum allowed size of <i>'. $max_size. 'KB</i>'; }
}
else { $result[$f] = 'File type extension <b>.'. $type. '</b> is not allowed'; }
}
}
// Return the result
$result2 = implode('<br /> ', $result);
echo '<h4>Files uploaded:</h4> '.$result2;
}
?>
and here is form that is used for picture uploading:
<form id="uploadform" action="uploaderimg.php" method="post" enctype="multipart/form-data" target="uploadframe" onSubmit="uploading(this); return false">
<br>
Select album:
<select name="album">
<?php
$query=mysql_query("SELECT id, name, user_id FROM album WHERE user_id = '$id'");
while($run=mysql_fetch_array($query)){
$album_id=$run['id'];
$album_name=$run['name'];
$album_user = $run['user_id'];
echo "<option value='$album_id'>$album_name</option>";
}
?>
</select>
<br /><br />
<h1>Chose your photo/s</h1>
<br>
<input type="file" name="files[]" />
<input type="submit" value="UPLOAD" id="sub" />
</form>
EDIT:
THis is error according to PHP(it's in first script that store uploaded file):
Notice: Undefined index: album in..
After conversing with the OP, the problem lay in this line:
<form id="uploadform" action="uploaderimg.php" method="post" enctype="multipart/form-data" target="uploadframe" onSubmit="uploading(this); return false">
Where onSubmit="uploading(this); return false" was at fault.

How to upload multiple files with Zend framework?

Even if I select 2 or more images, only one gets uploaded.
I have a simple form:
<form action="/images/thumbs" method="post" enctype="multipart/form-data">
<input name="file[]" id="file" type="file" multiple="" />
<input type="submit" name="upload_images" value="Upload Images">
</form>
Then in my controller:
public function thumbsAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
if (isset($_POST['upload_images'])) {
$names = $_FILES['file']['name'];
// the names will be an array of names
foreach($names as $name){
$path = APPLICATION_PATH.'/../public/img/'.$name;
echo $path; // will return all the paths of all the images that i selected
$uploaded = Application_Model_Functions::upload($path);
echo $uploaded; // will return true as many times as i select pictures, though only one file gets uploaded
}
}
}
}
and the upload method:
public static function upload($path)
{
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->addFilter('Rename', array(
'target' => $path,
'overwrite' => true
));
try {
$upload->receive();
return true;
} catch (Zend_File_Transfer_Exception $e) {
echo $e->message();
}
}
Any ideas why I get only one file uploaded?
Zend_File_Transfer_Adapter_Http actually has the information about the file upload. You just have to iterate using that resource:
$upload = new Zend_File_Transfer_Adapter_Http();
$files = $upload->getFileInfo();
foreach($files as $file => $fileInfo) {
if ($upload->isUploaded($file)) {
if ($upload->isValid($file)) {
if ($upload->receive($file)) {
$info = $upload->getFileInfo($file);
$tmp = $info[$file]['tmp_name'];
// here $tmp is the location of the uploaded file on the server
// var_dump($info); to see all the fields you can use
}
}
}
}

Categories