file upload a pdf in laravel - php

Hi everyone i need some help i work a program called file upload , but i dont get it what happen to the file i upload in laravel. in public folder there's a name called php4CA1.tmp every time i upload a pdf file please can anybody help me ? what is the meaning of this php4CA1.tmp or my code is wrong?
$request->validate([
'cover' => 'required',
'book' => 'required',
'name' => 'required',
'description' => 'required',
'price' => 'required|numeric'
]);
$image = $request->file('cover');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'),$new_name);
$book = $request->file('book');
$new_book_name = rand() . '.' . $book->getClientOriginalExtension();
$book->move(public_path('books'),$book);
$data = array(
'cover' => $new_name,
'book' => $new_book_name,
'name' => $request->name,
'description' => $request->description,
'price' => $request->price
);
Book::create($data);

Hi friend please follow as below you are passing the file instead of file name,
$book = $request->file('book');
$new_book_name = rand() . '.' . $book->getClientOriginalExtension();
$response = $book->move(public_path('books'),$new_book_name );

You are passing $book in
$book->move(public_path('books'),$book);
Use this:
$book = $request->file('book');
$new_book_name = rand() . '.' . $book->getClientOriginalExtension();
$book->move(public_path('books'),$new_book_name);

Related

laravel 9 " `C:\XAMPP\tmp\php6CB6`.`tmp`, " issue when uploading image

$request->validate([
'title' => 'required|unique:latests|max:255',
'description' => 'required',
'image' => 'required','mimes:jpg,png,jpeg', 'max:5048']);`
if($request->file('image')){
$image = $request->file('image');
$image_gen = hexdec(uniqid()). '.'. $image->getClientOriginalExtension();
Image::make($image)->resize(322, 500)->save(public_path('upload/image-folder/'. $image_gen));
$save_url = 'upload/image-folder'. $image_gen;`
}
$latest = new Latest();
$latest->title = $request->title;
$latest->description = $request->description;
$latest->$image = $save_url;
$latest->save();`
Here is the image for error column in database:
I've tried also this one :
'local' => ['driver' => 'local', 'root' => public_path(),
Unfortunately it didn't work i don't

Laravel and Guzzle fopen(): can´t find file uploading to an server

I´m trying to upload an image from my server to another one using an API.
I´ve uploaded to my server using native Storage facade and then, call the Guzzle function to upload the file to the other server.
The problem is that I can´t get the local of the file. Let´s see some code:
public function saveImage(Request $request)
{
// return $request;
$consorciado = Consorciado::where('id', '=', $request->consorciado_id)->first();
$documento = Documento::where('doc_id', '=', $request->id)->first();
$documento = new Documento();
$image = request()->file('f');
$documento->consorciado_id = $consorciado->id;
$documento->doc_id = $request->id;
$documento->tipo = $request->tipo;
$documento->remark = $request->remark;
$documento->idTematica = $request->idTematica;
$documento->field1 = $request->field1;
$documento->field2 = $request->field2;
$documento->field3 = $request->field3;
$documento->field4 = $request->field4;
$documento->field5 = $request->field5;
$filename = $consorciado->id . "_" . $documento->doc_id . "." . $image->getClientOriginalExtension();
$documento->nome = $filename;
// dd($doc);
// $file = fopen(Storage::disk('local') . '/' . file_get_contents($image), 'r');
// dd($file);
$client = new Client([
'base_uri' => 'http://gedocflex.com.br:8003/api/file',
]);
$response = $client->request('POST', 'http://gedocflex.com.br:8003/api/file', [
'multipart' => [
[
'name' => 'idTematica',
'contents' => '201'
],
[
'name' => 'f',
// 'contents' => $filename, file_get_contents($image)
'contents' => fopen('/' . $filename, file_get_contents($image), 'w+')
],
[
'name' => 'field1',
'contents' => '132.626.688-85'
],
[
'name' => 'field2',
'contents' => '7758'
],
[
'name' => 'field3',
'contents' => '404'
],
[
'name' => 'field4',
'contents' => '0'
],
[
'name' => 'field5',
'contents' => 'Marcello Dantas Correia'
],
[
'name' => 'remark',
'contents' => 'Enviando do meu servidor para o GED'
],
]
]);
return $response;
Storage::disk('local')->put('public/' . $filename, file_get_contents($image), 'public');
$documento->save(); //salva no meu banco
}
I´m using php artisan storage:link and the error is:
{message: "fopen(/1_1.jpeg): failed to open stream: No such file or directory",…}
exception: "ErrorException"
file: "/Users/marcellopato/Sites/contemplado/app/Http/Controllers/DocumentoController.php"
line: 234
message: "fopen(/1_1.jpeg): failed to open stream: No such file or directory"
trace: [{function: "handleError", class: "Illuminate\Foundation\Bootstrap\HandleExceptions", type: "->"},…]
As you can see, I get the name of the file, but not its path.
What I am doing wrong?
Anyone?
Thanks in advance!

Trying to upload multiple images using guzzlehttp client in laravel

I am trying to upload multiple images using guzzlehttp client. I have a form in which other type of data('id', 'date','name' e.t.c..) and images are there.
I want to save other data along with image upload through an Api Request.
I am able to save other data, but i am getting problem in uploading images.
In the API i am accessing my image file by
$request->file('images')
but it is showing empty.
My code for calling the API
$images = $request->file('images');
foreach ($images as $image)
{
$body[] = [
'Content-type' => 'multipart/form-data',
'name' => $image->getClientOriginalName(),
'contents' => fopen($image->getRealPath(), 'r')
];
}
$data = $request->all();
$client = new Client();
$response = $client->request('POST', $url, [
'multipart' => $body,
'json' => $data
]);
I'm handling the Api for uploading image below
if ($request->hasFile('images'))
{
$images = $request->file('images');
foreach ($images as $image)
{
$imageRules = [
'file' => 'mimes:png,jpeg,jpg,JPG|max:1024'
];
$imageMessages = [
'file.mimes' => 'One of the images/video is not valid. (only .png, .jpeg, .jpg, .mp4, .x-flv, .x-mpegURL, .MP2T, .3gpp, .quicktime, .x-msvideo, .x-ms-wmv are accepted)',
'file.max' => 'Image size cannot br more than 1 MB'
];
$imageValidator = Validator::make(['file' => $image], $imageRules, $imageMessages);
if ($imageValidator->fails())
{
return response()->json(['success' => false, 'error' => $imageValidator->messages()->first(), 'dashRedirectUrl' => $redirectRoute]);
}
}
$directPath = '/ticket/' . $ticket->id . '/mapping/' . $mappingId . '/images/';
foreach ($images as $image)
{
$option = ['isWatermark' => false];
$imageName = $this->uploadImageToServer($image, $directPath, $option);
$imgInsertData = [
'url' => $imageName,
'title' => $this->getImageTitle($image),
'ticket_mapping_id' => $mappingId,
'type_id' => 1,
];
TicketMappingGallery::create($imgInsertData);
}
}
Note :: My funciton uploadImageToServer() is custom function for uploading the images..
Any help would be appreciated. Drop comment if anything is not clear.
Try this one,
foreach ($image as $img) {
$body[] = [
'name' => 'image[]',
'image_path' => $img->getPathname(),
'image_mime' => $img->getmimeType(),
'image_org' => $img->getClientOriginalName(),
'contents' => fopen($img->getRealPath(), 'r')
];
}
$requestOptions = ['query' => $data, 'multipart' => $body
];

Laravel send mail with multiple product information

i have implemented multiple product upload and save the details to Database, i need to send the mail with inserted multiple product data to mail
My Controller:
public function store(Request $request)
{
$input = Input::all();
$destinationPath = public_path() . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'trade'; // upload path
$files = Input::file('file');
$length = 6;
$randomString = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
$trade = Trade::create(array(
'id' => $request->get('id'),
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'address1' => $request->get('address1'),
'address2' => $request->get('address2'),
'zip_code' => $request->get('zip_code'),
'country' => $request->get('country'),
'email' => $request->get('email'),
'phone' => $request->get('phone'),
'bank_name' => $request->get('bank_name'),
'account_number' => $request->get('account_number'),
'iban_number' => $request->get('iban_number'),
'swift_number' => $request->get('swift_number'),
'voucher_code' => $randomString . $request->get('voucher_code'),
));
foreach ($input['purchase_item'] as $k => $v) {
$file = $input['file'][$k];
if (!file_exists($destinationPath)) {
mkdir($destinationPath, 0777, true);
}
$extension = $file->getClientOriginalExtension();
$file_name = time() . '_' . $file->getClientOriginalName();
$fileName = $file_name; // renameing image
$file->move($destinationPath, $fileName);
$timestamp = strtotime($input['purchase_date'][$k]);
$new_date = date('Y-m-d', $timestamp);
$tradeins_products = TradeProduct::create(array(
'tradins_id' => $trade->id,
'product_id' => $input['product_id'][$k],
'application_id' => $input['application_id'][$k],
'brand_id' => $input['brand_id'][$k],
'purchase_date' => $new_date,
'purchase_item' => $input['purchase_item'][$k] ,
'file' => $fileName
));
$data = array(
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'product_name' => $tradein_product_name[0]['name'],
'address' => $request->get('address1'),
'phone' => $request->get('phone'),
'bank_name' => $request->get('bank_name'),
'account_number' => $request->get('account_number'),
'purchase_date'=>$new_date,
'country_email'=>$country_name[0]['email'],
'country_address1' =>$country_name[0]['address_1'],
'country_address2'=>$country_name[0]['address_2'],
'country_city'=>$country_name[0]['city'],
'country_state'=>$country_name[0]['state'],
'country_zipcode'=>$country_name[0]['zipcode'],
'voucher_code'=>$trade->voucher_code
);
Mail::send('frontend.mail_trade', $data, function($message) use ($data){
$message->to($data['email'], $data['first_name'].' '.$data['last_name'])->subject('Product Trade-in');
return Response::json(array('voucher_code' => $trade- >voucher_code,'first_name'=>$trade->first_name,'email'=>$trade->email,'phone'=>$trade->phone,'address1'=>$trade->address1,'zip_code'=>$trade->zip_code,'country'=>$trade->country,'country_name' => $country_name[0]['name'],'voucher_code1' => $trade->voucher_code,'country_address1' =>$country_name[0]['address_1'],'country_address2'=>$country_name[0]['address_2'],'country_city' =>$country_name[0]['city'],'country_state' =>$country_name[0]['state'],'country_zipcode' =>$country_name[0]['zipcode'], 'country_email' =>$country_name[0]['email'], 'company_name' => $country_name[0]['company_name']));
}
So Above i done inserting two tables, tradin, and tradein products, so tradein products contain multiple product upload and insertion, so i need to show like below on mail
Product Data:
1)product name
-Sony
-Samsung
2)Application Name:
-Handsfree
-Wireless
So how is this possible with using foreach or any other alternate way to do it to show the Data's in mail template,
My Mail Template:
<h3>Cash Back</h3>
<p>Product Name:{{$product_name}} </p>
<p>Name: {{$first_name}} {{$last_name}}
</p>
<p>Address: {{$address}}</p>
<p>Phone:{{$phone}} </p>
<p>Bank: {{$bank_name}}</p>
<p>Account Number:{{$account_number}} </p>
<p>Voucher Code:{{$voucher_code}} </p>
<p>Company Email:{{$country_email}} </p>
<p>Company Address1:{{$country_address1}} </p>
<p>Company Address2:{{$country_address2}} </p>
<p>Company City:{{$country_city}} </p>
<p>Company State:{{$country_state}} </p>
<p>Company Zipcode:{{$country_zipcode}} </p>
<p>Purchase Date: {{$purchase_date}}</p>
Take note that first parameter is your email view, and the second parameter is the data you want to pass to your view. for example:
Mail::send('frontend.mail_trade', $productsData, function($message) use ($data){
// your code
});

zf2 how to upload files, more than 1 file

I refer to http://samsonasik.wordpress.com/2012/08/31/zend-framework-2-creating-upload-form-file-validation/ and follow this, I can upload 1 file successfully by using rename filter in ZF2.
However when I use this way to upload 2 files, it goes wrong. I paste my code as following:
$this->add(array(
'name' => 'bigpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Big Pic'
)
));
$this->add(array(
'name' => 'smallpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Small Pic'
)
));
<div class="row"><?php echo $this->formRow($form->get('smallpicture')) ?></div>
<div class="row"><?php echo $this->formRow($form->get('bigpicture')) ?></div>
$data = array_merge(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($data);
if ($form->isValid()) {
$product->exchangeArray($form->getData());
$picid = $this->getProductTable()->saveProduct($product);
$pathstr = $this->md5path($picid);
$this->folder('public/images/product/'.$pathstr);
//move_uploaded_file($data['smallpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg');
//move_uploaded_file($data['bigpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg');
$fileadaptersmall = new \Zend\File\Transfer\Adapter\Http();
$fileadaptersmall->addFilter('File\Rename',array(
'source' => $data['smallpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg',
'overwrite' => true
));
$fileadaptersmall->receive();
$fileadapterbig = new \Zend\File\Transfer\Adapter\Http();
$fileadapterbig->addFilter('File\Rename',array(
'source' => $data['bigpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg',
'overwrite' => true
));
$fileadapterbig->receive();
}
the above are form,view,action.
using this way, only the small picture uploaed successfully. the big picture goes wrong.
a warning flashed like the following:
Warning:move_uploaded_file(C:\WINDOWS\TMP\small.jpg):failed to open stream:Invalid argument in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Warning:move_uploaded_file():Unable to move 'C:\WINDOWS\TMP\php76.tmp'
to 'C:\WINDOWS\TEMP\big.jpg' in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Who can tell me how to upload more than 1 file in this way. you know, the rename filter way similar to above. thanks.
I ran into the same problem with a site i did. The solution was to do the renaming in the controller itself by getting all the images and then stepping through them.
if ($file->isUploaded()) {
$pInfo = pathinfo($file->getFileName());
$time = uniqid();
$newName = $pName . '-' . $type . '-' . $time . '.' . $pInfo['extension'];
$file->addFilter('Rename', array('target' => $newName));
$file->receive();
}
Hope this helps point you in the right direction.
I encountered the same problem and i managed to make it work using the below code;
$folder = 'YOUR DIR';
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination($folder);
foreach ($adapter->getFileInfo() as $info) {
$originalFileName = $info['name'];
if ($adapter->receive($originalFileName)) {
$newFilePath = $folder . '/' . $newFileName;
$adapter->addFilter('Rename', array('target' => $newFilePath,
'overwrite' => true));
}
}

Categories