i used the following code to store multiple images to database every thing works fine storing and displaying uploading what i need is when i upload 3 photo at once three rows are created for single uploading how could i store path of multiple images in a one single row
class Upload_Rename {
const ALLOWED_TYPES = "jpg,gif,png";
public static function generate_new_name($extension, $uppercase = true, $prefix = '', $sufix = '') {
$new_name = $prefix . uniqid() . '_' . time() . $sufix;
return ($uppercase ? strtoupper($new_name) : $new_name) . '.' . $extension;
}
public static function check_and_get_extension($file) {
$file_part = pathinfo($file);
$allowed_types = explode(",", Upload_Rename::ALLOWED_TYPES);
if (!in_array($file_part['extension'], $allowed_types)) {
throw new Exception('Not ok.. bad bad file type.');
}
return $file_part['extension'];
}
public function upload($file, $target_destination) {
if (!isset($file['tmp_name'])) {
throw new Exception('Whaaaat?');
}
$_name = $file['name'];
$_tmp = $file['tmp_name'];
$_type = $file['type'];
$_size = $file['size'];
$file_extension = '';
try {
$file_extension = Upload_Rename::check_and_get_extension($_name);
} catch (Exception $e) {
throw new Exception('Ops.. file extension? what? ' . $e->getMessage());
}
$new_name = Upload_Rename::generate_new_name($file_extension, true, 'whaat_', '_okey');
$destination = $target_destination . DIRECTORY_SEPARATOR . $new_name;
move_uploaded_file($_tmp, $destination);
return $destination;
}
public function multiple_files($files, $destination) {
$number_of_files = isset($files['tmp_name']) ? sizeof($files['tmp_name']) : 0;
$errors = array();
$paths=array();
for ($i = 0; $i < $number_of_files; $i++) {
if (isset($files['tmp_name'][$i]) && !empty($files['tmp_name'][$i])) {
try {
$path=$this->upload(array(
'name' => $files['name'][$i],
'tmp_name' => $files['tmp_name'][$i],
'size' => $files['size'][$i],
'type' => $files['type'][$i]
), $destination);
$paths[]=$path;
} catch (Exception $e) {
array_push($errors, array('file' => $files['name'][$i], 'error' => $e->getMessage()));
}
}
}
return $paths;
}
}
if ($_FILES) {
$upload = new Upload_Rename();
$destination = 'upload';
$paths=$upload->multiple_files($_FILES['myfile'], $destination);
//Fill this with correct information
$mysql_hostname = "";
$mysql_user = "";
$mysql_password = "";
$mysql_database = "";
$tbl_name="test";
$pathfield_name='path';
//
$mysql= new mysqli($mysql_hostname,$mysql_user,$mysql_password,$mysql_database);
foreach($paths as $path){
$query='INSERT INTO `'.$tbl_name.'` (`'.$pathfield_name.'`) VALUES ("'.$mysql->escape_string($path).'");';
$mysql->query($query);}
$mysql->close();
}
?>
<form method="post" enctype="multipart/form-data">
<?php for ($i = 0; $i < 10; $i++): ?>
file: <input type="file" name="myfile[]"><br>
<?php endfor; ?>
<input type="submit">
</form>
i used this code to create table in sql
CREATE TABLE IF NOT EXISTS `test` (
`path` text(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Fetch path feild first and store in one variable then insert
foreach($paths as $path){ $pathfield_name.=$pathfield_name."/"; }
$query='INSERT INTO `'.$tbl_name.'` (`'.$pathfield_name.'`) VALUES ("'.$mysql->escape_string($path).'");';
$mysql->query($query);
Related
i want store the images for product the product having multiple images the problem is that i want to update the images problem is images are updated but the entry never goes to database. instead it stores same entry two times.
if($request->hasfile('image')) { //here i got images
$file = $request->file('image');
$file_count= count($file); //for updating multiple images
for ($i=0; $i < $file_count; $i++) {
$imagesize = $file[$i]->getClientSize();
$imageexten = $file[$i]->getClientOriginalExtension();
$product_image_count = count($request->productimagename);
for ($i=0; $i < $product_image_count; $i++) {
if($file_count != 1) {
$new_name = $request->productimagename[$i].$i.".".$imageexten;
} else {
$new_name = $request->productimagename[$i].".".$imageexten;
}
$product_image_path ='images/frontendimage/product_image/'.$new_name;
Image::make($file[$i])->save($product_image_path);
foreach ($product->images as $key => $value) {
product_image::find($value->id)->where('product_id','=',$product->id)
->update(['image_name'=> $new_name,'image_url'=>$product_image_path,
'modified_by'=>Auth::user()->id]);
}
}
}
}
if ($request->has('unit_images'))
{
$promotion = [];
foreach ($request->file('unit_images') as $key => $file) {
$filenameWithExt = $file->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$fileNameToStore = uniqid() . '.' . $extension;
$path = $file->storeAs("$directory/unit_images/$b/$unit_num", $fileNameToStore, 'public');
$this->validate($request, [
'images' => 'dimensions:min_width=250,min_height=250'
]);
$b_id = $request->building_name;
$unitimg = UnitImage::where('unit_id', '=', $unit_store_id)->get();
$new=strlen($unitimg);
if ($new!='2') {
foreach ($unitimg as $get2) {
$get2->delete();
}
$nn=New UnitImage();
$nn->images = $path;
$nn->unit_id = $unit_store_id;
$nn->save();
}
if ($new=='2') {
$nn = New UnitImage();
$nn->images = $path;
$nn->unit_id = $unit_store_id;
$nn->save();
}
}
}
Input Field -
<input type="file" name="images[]" class="form-control" multiple required />
Controller -
$imagesName = array();
$imagesPath = array();
if($files=$request->file('images')){
foreach (Input::file('images') as $file) {
$name = strtolower($file->getClientOriginalName());
$name = preg_replace('/\s+/', '_', $name);
$img = Image::make($file);
$path = 'your/path/'.$name;
$img->save($path);
$imagesName[] = $name;
$imagesPath[] = $path;
}
}
This will upload multiple images to your server and you will get uploaded image names from $imagesName[] and path from $imagesPath[].
Now you can use those according to your BD structure.
The following php pdf to image code with imagick in codeigniter framework has a problem in the controller, imagick cannot read my file pdf.
error:
[codeigniter] An uncaught Exception was encountered Type: ImagickException Message: Failed to read the file in Codeigniter.
controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Files_upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('files');
}
function index(){
$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result();
$data = array();
if($this->input->post('submitForm') && !empty($_FILES['upload_Files']['name'])){
$filesCount = count($_FILES['upload_Files']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['upload_File']['name'] = $_FILES['upload_Files']['name'][$i];
$_FILES['upload_File']['type'] = $_FILES['upload_Files']['type'][$i];
$_FILES['upload_File']['tmp_name'] = $_FILES['upload_Files']['tmp_name'][$i];
$_FILES['upload_File']['error'] = $_FILES['upload_Files']['error'][$i];
$_FILES['upload_File']['size'] = $_FILES['upload_Files']['size'][$i];
$uploadPath = 'uploads/files/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('upload_File')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
}
if(!empty($uploadData)){
//Insert file information into the database
$insert = $this->files->insert($uploadData);
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
}
$this->load->helper('url');
$ImageName = $_FILES['upload_File']['name'];
$loc = base_url().$uploadPath.$ImageName;
echo $ImageName;
echo $loc;
$im = new imagick($loc);
$noOfPagesInPDF = $im->getNumberImages();
if ($noOfPagesInPDF) {
for ($i = 0; $i < 1; $i++) {
$url = $loc.'['.$i.']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage("uploads/files/img/".($i+1).'-'.$ImageName.'.jpg');
}
}
for($i = 0; $i<1;$i++) {
$img = "uploads/files/img/".($i+1).'-'.$ImageName.'.jpg';
$display .= "<img src='$img' title='Page-$i' /><br>";
}
$message = "PDF converted to JPEG sucessfully!!";
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
}
}
Solved
Is Correct Code
$ImageName= $fileData['file_name'];
$loc = realpath(APPPATH.'../uploads/files/').'/'.$ImageName;
Or you can just do
$loc = $fileData['full_path'];
This will work (tested):
//$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result(); // same at bottom??
$message = '';
$display = '';
if ($this->input->post('submitForm') && !empty($_FILES['userfile']['name'])) {
$uploadPath = FCPATH . 'uploads/files/';
if (!is_dir($uploadPath) && mkdir($uploadPath, DIR_WRITE_MODE, true) == false) {
show_error('Folder cannot be made!');
}
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
// change input field to <input type="file" name="userfile">
if (!$this->upload->do_upload()) {
$this->session->set_flashdata('statusMsg', $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$uploadData['file_name'] = $fileData['file_name'];
$uploadData['created'] = date("Y-m-d H:i:s");
$uploadData['modified'] = date("Y-m-d H:i:s");
$insert = $this->files->insert($uploadData);
$insert = true;
if (!$insert) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', 'Database error. Please try again');
} else {
$this->session->set_flashdata('statusMsg', 'Files uploaded successfully.');
if ($fileData['file_ext'] == '.pdf') {
try {
$newPath = $uploadPath . 'img/';
if (!is_dir($newPath) && mkdir($newPath, DIR_WRITE_MODE, true) == false) {
throw new Exception('Folder cannot be made!');
}
$ImageName = $fileData['raw_name'];
$loc = $fileData['full_path'];
$im = new Imagick($loc);
$pdfPageCount = $im->getNumberImages();
if ($pdfPageCount > 0) {
for ($i = 0; $i < $pdfPageCount; $i++) {
$url = $loc . '[' . $i . ']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage($newPath . ($i + 1) . '-' . $ImageName . '.jpg');
$img = base_url("uploads/files/img/" . ($i + 1) . '-' . $ImageName . '.jpg');
$display .= "<img src='$img' title='Page-$i' /><br>";
}
echo $display; // debugging
$this->session->set_flashdata('statusMsg', "PDF converted to JPEG(s) sucessfully!");
}
} catch (Exception $e) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', $e->getMessage());
}
} else {
echo 'not a pdf'; // debugging only
}
}
}
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
Please note the input file field should now look like this:
<input type="file" name="userfile" />
You will also have to revise:
$this->files->insert($uploadData) function
I am trying to upload image to database MySQL. But I have a problem, when I am trying to upload one image, the image inserted twice.
For example:
I have "A.jpg" if I try to upload it
the inserted data will be like "A.jpg,A.jpg"
What I want in database "A.jpg"
and if I try to upload multiple images like "A.jpg,B.jpg and C.jpg"
the inserted data will be like "B.jpg,B.jpg,C.jpg,C.jpg"
What I want in database "A.jpg,B.jpg,C.jpg"
I've tried to search on google but no results, anyone can help me to resolve this problem ? Thanks
Here is my code :
include('koneksi.php');
date_default_timezone_set('Asia/Jakarta');
$id_user = $_POST['id_user'];
$caption = $_POST['caption'];
$files = [];
foreach($_FILES['files']['name'] as $i => $name) {
$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];
$explode = explode('.', $name);
$ext = end($explode);
$updatdName = $explode[0] . time() .'.'. $ext;
$path = 'gallery/';
$path = $path . basename( $updatdName );
if(empty($_FILES['files']['tmp_name'][$i])) {
$errors[] = 'Please choose at least 1 file to be uploaded.';
}else {
$allowed = array('jpg','JPG','jpeg','JPEG','gif','GIF','bmp','BMP','png','PNG');
$max_file_size = 1024*1024*2;; // 2MB
if(in_array($ext, $allowed) === false) {
$errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
}
if($size > $max_file_size) {
$errors[] = 'The file <b>'.$name.'</b> size is too hight.';
}
}
if(empty($errors)) {
// if there is no error then set values
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$errors = array();
if(!file_exists('gallery')) {
mkdir('gallery', 0777);
}
if(move_uploaded_file($tmp, $path)) {
echo '<script>window.history.back()</script>';
}else {
echo 'Something went wrong while uploading
<b>'.$name.'</b>';
}
}else {
foreach($errors as $error) {
echo '<p>'.$error.'<p>';
}
}
}
if(!empty($files)) {
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$names = implode(',', $files['file_name']);
$sizes = implode(',', $files['size']);
$types = implode(',', $files['type']);
$sql="INSERT into status VALUES(NULL, '$id_user', '$names','$caption','foto',NOW()); ";
mysqli_query($koneksi, $sql);
}
You're setting $files['file_name'][] in the while loop and also right before inserting into the DB. You just need to remove 2nd call to $files['file_name'][] = $updatdName;
Here is a simplified version of what you're doing.
<?php
$_FILES[] = ['name' => 'A'];
$_FILES[] = ['name' => 'B'];
$_FILES[] = ['name' => 'C'];
$files = [];
foreach ($_FILES as $file) {
$updatdName = $file['name'];
// You're setting it here
$files['file_name'][] = $updatdName;
}
if (!empty($files)) {
// And also here.
$files['file_name'][] = $updatdName;
$names = implode(',', $files['file_name']);
echo $names;
}
This question already has answers here:
Multiple returns from a function
(32 answers)
Closed 6 years ago.
I am trying to create a simple uploader class to use uploading multiple images. I need to return file info from uploadFiles method and use it inside another method (uploadGalleryImages). However if I use return $result then foreach loop stops after first file is uploaded. If I don't return it and just use print_r($result) I can upload all files and see the object in chrome's network tab. Here is my simplified code:
public function uploadGalleryImages() {
$upload_image = $this->uploadFiles($_FILES['image']);
}
private function reArrayFiles($files) {
$array = array();
$file_count = count($files['name']);
$file_keys = array_keys($files);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$array[$i][$key] = $files[$key][$i];
}
}
return $array;
}
private function uploadFiles($files = array()) {
$upload_dir = IMAGE_UPLOAD_DIR;
$thumb_dir = $upload_dir . 'thumbnails/';
$file_array = $this->reArrayFiles($files);
foreach ($file_array as $file) {
$base_name = pathinfo($file['name'], PATHINFO_FILENAME);
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$counter = 1;
while(file_exists($upload_dir . $file['name'])) {
$file['name'] = $base_name . $counter . '.' . $extension;
$counter++;
};
if (move_uploaded_file($file['tmp_name'], $upload_dir . $file['name'])) {
$result = new \stdClass();
$result->file_name = $file['name'];
$result->extension = $extension;
//print_r($result);
return $result; // Stops after first file uploaded
} else {
return false;
}
}
}
Store all picture objects in array and return it. Simple example:
$pics = [];
foreach ($file_array as $file) {
if (move_uploaded_file($file['tmp_name'], $upload_dir . $file['name'])) {
$result = new \stdClass();
$result->file_name = $file['name'];
$result->extension = $extension;
$pics[] = $result;
}
}
return $pics;
I'm trying to upload a file in my symfony2 project by using a simple Form.
I did read the official doc of symfony but Id want only move my file to directory and update a field in a db table (called user) not create an entity for the file. I use an example I succeed to upload but in .tmp extension (ex. phpXXX.tmp). Any Ideas please.
here my code :
Document.php:
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Document
{
private $file;
private $subDir;
private $filePersistencePath;
/** #var string */
protected static $uploadDirectory = '%kernel.root_dir%/../styles/images';
static public function setUploadDirectory($dir)
{
self::$uploadDirectory = $dir;
}
static public function getUploadDirectory()
{
if (self::$uploadDirectory === null) {
throw new \RuntimeException("Trying to access upload directory for profile files");
}
return self::$uploadDirectory;
}
public function setSubDirectory($dir)
{
$this->subDir = $dir;
}
public function getSubDirectory()
{
if ($this->subDir === null) {
throw new \RuntimeException("Trying to access sub directory for profile files");
}
return $this->subDir;
}
public function setFile(File $file)
{
$this->file = $file;
}
public function getFile()
{
return new File(self::getUploadDirectory() . "/" . $this->filePersistencePath);
}
public function getOriginalFileName()
{
return $this->file->getClientOriginalName();
}
public function getFilePersistencePath()
{
return $this->filePersistencePath;
}
public function processFile()
{
if (! ($this->file instanceof UploadedFile) ) {
return false;
}
$uploadFileMover = new UploadFileMover();
$this->filePersistencePath = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDirectory(),$this->subDir);
}
}
UploadFileMover
use Symfony\Component\HttpFoundation\File\UploadedFile;
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath) {
$originalName = $file->getFilename();
// use filemtime() to have a more determenistic way to determine the subpath, otherwise its hard to test.
// $relativePath = date('Y-m', filemtime($file->getPath()));
$targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
$targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
$ext = $file->getExtension();
$i = 1;
while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
if ($ext) {
$prev = $i == 1 ? "" : $i;
$targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
} else {
$targetFilePath = $targetFilePath . $i++;
}
}
$targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
if (!is_dir($targetDir)) {
$ret = mkdir($targetDir, umask(), true);
if (!$ret) {
throw new \RuntimeException("Could not create target directory to move temporary file into.");
}
}
$file->move($targetDir, basename($targetFilePath));
return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
}
}
controller :
public function uploadImgAction(Request $req) {
if ($req->getMethod() == 'POST') {
$status = 'success';
$uploadedURL = '';
$message = 'Image modifiée';
$image = $req->files->get('fileselect');
if (($image instanceof UploadedFile) && ($image->getError() == '0')) {
if ($image->getSize() < 2000000) {
$originalName = $image->getClientOriginalName();
$name_array = explode('.', $originalName);
$file_type = $name_array[sizeof($name_array) - 1];
$valid_filetypes = array('jpg', 'jpeg', 'bmp', 'png');
if (in_array(strtolower($file_type), $valid_filetypes)) {
//télécharegement du fichier
//Start Uploading File
$document = new Document();
$document->setFile($image);
$document->setSubDirectory('uploads');
$document->processFile();
$uploadedURL=$uploadedURL = $document->getUploadDirectory() . DIRECTORY_SEPARATOR . $document->getSubDirectory() . DIRECTORY_SEPARATOR . $image->getBasename();
} else {
$status = 'echoue';
$message = 'Seuls les extensions png, jpg, jpeg et bmp sont acceptées';
}
} else {
$status = 'echoue';
$message = 'La taille du fichier dépasse 2MB';
}
} else {
$status = 'echoue';
$message = 'Une erreur de télechargement';
}
return $this->render('PIRecrutementBundle:xx:xxx.html.twig');
//return new Response($uploadedUrl);
} else {
return $this->render('xxxBundle:xx:xxx.html.twig');
}
}
Exactly as Tomasz Turkowski said the solution is to change the base-name of the file by its real name using $file->getClientOriginalName( in class UploadFileMover.
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath)
{
// $originalName = $file->getFilename();
$originalName = $file->getClientOriginalName();
// use filemtime() to have a more determenistic
Without changing anything like .tmp to some other extention or the original name, you can still store the same obtained path in DB. I think you can write a query to store the path in DB after this statement in your controller
$uploadedURL=$uploadedURL = $document->getUploadDirectory() . DIRECTORY_SEPARATOR . $document->getSubDirectory() . DIRECTORY_SEPARATOR . $image->getBasename();
By using the variable $uploadURL like
{
//in your methodAction
"Update [YOUR TABLE] SET [PATHcolomn]=".$uploadURL." WHERE USERid=".$user->getUid()." "
$path= "SELECT [PATHcolomN] FROM [YOUR TABLE] WHERE USERid=".$user->getUid()." "
$this->data['path']=$path;
return $this->data;
}
After Updating, you can fetch this path in the place of <img src= {{ path }} >