Laravel 6 - How to upload multi file through laravel? - laravel

I wrote these code for upload files through laravel 6.
But I only success for upload one file,even I am sure I got all files while uploading by check from dd($request->files)
in the begining the $index = 0 and in the end it change to 1,first round is ok but the it didn't continue to second run.
I don't know why,please help! thank you~
if($request->hasFile('files')){
$index = 0;
foreach($request->files as $key=>$file){
$originalName = $file[$index]->getClientOriginalName();
$size = $file[$index]->getClientSize();
$ext = $file[$index]->getClientOriginalExtension();
$newName = date('Ymd').mt_rand(100,999).$originalName;
$savePath = '/attachments/'.$newName;
$movePath = base_path().'/public/attachments/'.$newName;
$file[$index]->move(base_path().'/public/attachments',$newName);
$attachment = new attachment();
$attachment->bulletin_id = $bulletin->id; //already got this value before
$attachment->original_name = $originalName;
$attachment->name = $newName;
$attachment->type = $file[$index]->getClientMimeType();
$attachment->path = $savePath;
$attachment->size = ($size/1000);
$attachment->save();
++$index;
}
}

You try this way and it is simple
foreach($request->file('files') as $key=>$file){
$originalName = $file->getClientOriginalName();
$size = $file->getClientSize();
$ext = $file->getClientOriginalExtension();
$newName = date('Ymd').mt_rand(100,999).$originalName;
$savePath = '/attachments/'.$newName;
$movePath = base_path().'/public/attachments/'.$newName;
$file->move(base_path().'/public/attachments',$newName);
$attachment = new attachment();
$attachment->bulletin_id = $bulletin->id; //already got this value before
$attachment->original_name = $originalName;
$attachment->name = $newName;
$attachment->type = $file->getClientMimeType();
$attachment->path = $savePath;
$attachment->size = ($size/1000);
$attachment->save();
}

Related

laravel - foreach repeat many times

I have two model : User & Book. I want create a book for each user with a specific QR code
$users = User::get();
$date = ... ;
$finalCount = 0;
$code = 150;
$userCount = count($users);
foreach ($users as $user) {
$book = new Book();
$book->unique_id = uniqid('', true);
$book->user_id = $user->unique_id;
$book->code = "PP-" . strval(mt_rand(100, 999)) . strval($code);
$book->create_date = $date;
$book->status = 'active';
$book->save();
$QRCode = new BaconQrCodeGenerator;
$file = public_path('/images/book/' . $book->code . '.png');
$QRCode->encoding('UTF-8')
->format('png')
->merge('/public/image/logo.png', .15)
->size(1000)
->generate($book->unique_id, $file);
if (File::exists($file))
$finalCount++;
$code++;
if ($finalCount == $userCount)
break;
}
After this function called, i have 20 book for each user. I used an if statement for break the loop ( if ($finalCount == $userCount) ) but it doesn't work.
I can't understand whats going on here and also i have not any error log
Instead of
$file = public_path('/images/book/' . $book->code . '.png');
try
$file = public_path().'/images/book/' . $book->code . '.png';

PHPExcel Image include

I tried hard, just wanna display barcode image in A1 cell. it works well in html. But not in PhpExcel. thanks in advance.
$generator = new BarcodeGeneratorPNG();
$wizard = new PHPExcel_Helper_HTML();
$cellText = '<img src="data:image/png;base64,' . base64_encode($generator->getBarcode('081231723837', $generator::TYPE_CODE_128)) . '">';
$richText = $wizard->toRichTextObject($cellText);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $richText);
Try whith:
https://github.com/davidscotttufts/php-barcode
generating barcode.png
$filepath = 'barcode.png';
$text = '1234567890123';
$size = "80";
$orientation = "horizontal";
$code_type = "code128";
$print = "true";
$sizefactor = "0.8";
barcode( $filepath,$text, $size, $orientation, $code_type, $print, $sizefactor );
Report:
$imgBarcode = imagecreatefrompng('bar_code.png');
$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
$objDrawing->setDescription('barcode');
$objDrawing->setImageResource($imgBarcode);
$objDrawing->setHeight(100);
$objDrawing->setCoordinates('A1');
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());

Laravel Thumbnail Can't read Original Image

I am trying to store user info including a pic in Laravel 5.3. Here is the relevant code:
if ( isset($request->image) )
{$path = $request->file('image')->store('public/users');}
$user = User::find($request->id);
if (isset($path))
{$user->image = $path;}
$user->name = $request->name;
$user->email = $request->email;
$user->active = $request->active;
$user->admin = $request->admin;
$user->address = $request->address;
$user->country_id = $request->country_id;
if ($request->ageverified = 1)
{$user->ageverified = 1;}
if ($request->verifieddate <> '')
{$user->verifieddate = $request->verifieddate;}
$user->verify_notes = $request->verify_notes;
$user->publisher = $request->publisher;
$user->paypal = $request->paypal;
$user->proname = $request->proname;
if (isset($path)) {
$file = Storage::url($path);
$tpath = basename($path);
Image::make($path)->resize(100,
100)->save('public/users/thumbs/'.tpath);
$user->thumbnail = $tpath;
}
$user->save();
The image is stored OK but when I get to making the thumbnail I am getting:
NotReadableException in AbstractDecoder.php line 302: Image source not readable
I have tried everything but am really stuck!
I have sorted this out in a laracast forum - see https://laracasts.com/discuss/channels/laravel/53-image-source-not-readable

"Value of 'null' is not valid for stream"

Attempting to download an image from a URL into memory. Getting an error on the response stream.
Exception calling "FromStream" with "1" argument(s): "Value of 'null' is not valid for 'stream'."
Function Download-Image {
$req = [System.Net.WebRequest]::Create
("http://www.wired.com/images_blogs/business/2012/12/google.jpg")
$response = $req.GetResponse()
$ResponseStream = $Response.GetResponseStream()
[System.IO.Stream]$stream = $ResponseStream
#$response.close()
}
[byte[]]$image = Download-Image
Add-Type -AssemblyName System.Windows.Forms
$img = [System.Drawing.Image]::FromStream([System.IO.MemoryStream]$image)
[System.Windows.Forms.Application]::EnableVisualStyles()
$pictureBox = new-object Windows.Forms.PictureBox
$pictureBox.Width = $img.Width
$pictureBox.Height = $img.Height
$pictureBox.Image = $img
$form = new-object Windows.Forms.Form
$form.Width = $img.Width
$form.Height = $img.Height
$form.AutoSize = $True
$form.AutoSizeMode = "GrowAndShrink"
$form.Icon = $icon
$form.controls.add($pictureBox)
$form.Add_Shown( { $form.Activate() } )
$form.ShowDialog()
You need to return value from function after assignment:
Function Download-Image {
$req = [System.Net.WebRequest]::Create
("http://www.wired.com/images_blogs/business/2012/12/google.jpg")
$response = $req.GetResponse()
$ResponseStream = $Response.GetResponseStream()
[System.IO.Stream]$stream = $ResponseStream
#$response.close()
$req
}
In your case $image variable just have a value of $null:
[byte[]]$image = Download-Image
Updated:
To download image as byte array you can use solution from this post:
var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");

access folder outside CodeIgniter

I've been to trying to upload images using code igniter and it works perfectly when the upload folder is just outside of application folder. But my problem is when I try to access folder which is outside whole code igniter folder it is throwing me a error. How to access the folder outside the code igniter folder? I tried $_SERVER['DOCUMENT_ROOT']. But it dint help.
$name = $_POST['name'];
$id = $_POST['id'];
if (isset($_FILES['upload']['name'])) {
// total files //
$count = count($_FILES['upload']['name']);
// all uploads //
$uploads = $_FILES['upload'];
for ($i = 0; $i < $count; $i++) {
if ($uploads['error'][$i] == 0) {
$firstimage = $uploads['name'][$i];
$secondimage = $uploads['name'][$i];
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);
$config2['image_library'] = 'gd2';
$config2['source_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i];
$config2['new_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/thumbnail/'.$uploads['name'][$i];
$config2['maintain_ratio'] = FALSE;
$config2['create_thumb'] = TRUE;
$config2['thumb_marker'] = '_thumb';
$config2['width'] = 75;
$config2['height'] = 50;
$config2['overwrite'] = TRUE;
$this->image_lib->initialize($config2);
$this->load->library('image_lib',$config2);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
$config3['image_library'] = 'gd2';
$config3['source_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i];
$config3['new_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/resize/'.$uploads['name'][$i];
$config3['maintain_ratio'] = FALSE;
$config3['create_thumb'] = TRUE;
$config3['thumb_marker'] = '_thumb';
$config3['width'] = 470;
$config3['height'] = 470;
$config3['overwrite'] = TRUE;
$this->image_lib->initialize($config3);
$this->load->library('image_lib',$config3);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
}
}
$this->load->view('head');
$data = array(
'name' => $name,
'id' => $id
);
After discussing in comments, the problem is likely the move_uploaded_file() function is trying to move the file to a directory that doesn't exist yet.
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);
Before the file can be moved the folder needs to be created. If $id is new, it has probably not been created yet. So...
if (!is_dir($_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id)) {
mkdir($_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id);
}
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);

Resources