I'm trying to upload files via API, in POSTMAN I can do it perfectly. However when doing in my application is not accepted.
Store in Controller:
public function store(Request $request)
{
$data = $request->validate([
'projeto_id' => 'required|integer',
'name' => 'required|string|max:255',
'logo' => 'nullable|image|mimes:jpeg,png,jpg|max:2000',
'telephone' => 'required|string|max:255',
'desc' => 'required|string',
'quantity' => 'required|integer|gt:0|lt:51',
'sequential' => 'required|integer|gt:0',
]);
$user = Auth::user()->id;
if($user != Auth::id()){
abort(403);
}
//UPLOAD IMAGEM DO GRUPO
$logo = $request['logo'];
// Check if a profile image has been uploaded
if ($request->has('logo')) {
// Get image file
$image = $request->file('logo');
// Make a image name based on user name and current timestamp
$name = Str::slug($user.'_'.time());
// Define folder path
$folder = '/uploads/images/'.$user.'/groupimg/logo/';
// Make a file path where image will be stored [ folder path + file name + file extension]
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
// Upload image
$this->uploadOne($image, $folder, 'public', $name);
// Set user profile image path in database to filePath
$logo = $filePath;
}
$gPrivado = '0';
if($request->has('private')){
$gPrivado = '1';
}
$i = 0;
$delayCounter = 0;
$sequential = $data['sequential'];
while ($i < (int)$data['quantity']) {
$delay = $delayCounter + rand(10, 15);
CreateGroups::dispatch($data['name'] . " {$sequential}", $logo , $data['desc'], $gPrivado, [$data['telephone']], $data['projeto_id'], auth()->user())
->delay(Carbon::now()
->addSeconds($delay));
$delayCounter = $delay;
$i++;
$sequential++;
}
return redirect()->back()->with('success', 'Grupos adicionados em fila de criação, aguarde alguns minutos .');
}
Use Job to proccess:
public function handle()
{
$user = $this->user;
if ($user->instance_connected) {
$ZApi = new ZApi($user->zapi_instance_id, $user->zapi_token);
$createdGroup = $ZApi
->createGroup($this->name, $this->phones);
sleep(3);
foreach($createdGroup->groupInfo as $informacoes){
$linkInvite = $ZApi->getGroupInvite($informacoes->id);
$idGroup = $informacoes->id;
}
//DESCRICAO DO GRUPO
$descricao = $this->desc;
$setDescricao = $ZApi->setGroupDescription($idGroup, $descricao);
//GRUPO PRIVADO
if ($this->private == '1'){
$grupoPrivado = $ZApi->setGroupMessages($idGroup, 'true');
$adminOnly = $ZApi->setGroupEdit($idGroup, 'true');
}
$setImg = $ZApi->groupImage($idGroup, $this->logo);
The last line send to API, I'm using Guzzle
And this is my API function
public function groupImage(string $groupId, string $value)
{
return $this->doRequest2('POST', "group-pic", [
'multipart' => [
[
'name' => 'phone',
'contents' => $groupId,
],
[
'Content-type' => 'multipart/form-data',
'name' => 'file',
'contents' => fopen('storage'.$value, 'r'),
]
]
]);
}
But get this error response
GuzzleHttp\Exception\ClientException Client error: POST http://localhost:8081/api/danilo/group-pic resulted in a 400 Bad Request response: {"status":"Error","message":"File parameter is
required!"}
Can someone help me?
Related
I received help to solve how to delete files uploaded by using the Cakephp Upload package. However, there seems to be a problem with how I update the values of the photo and dir fields. By using unlink I was able to delete the files perfectly, but there seems to be a problem when I try to set the values to null. I made a function to test it out:
public function deletePhoto2($id)
{
// $this->request->allowMethod(['post']);
if ($this->request->is(['patch', 'post', 'put'])) {
$brigada = $this->Brigadas
->findById($id)
->firstOrFail();
$brigada->dir = null;
$brigada->photo = null;
if ($this->Brigadas->save($brigada)) {
$this->Flash->success(__('Your team data has been saved.'));
return $this->redirect(['action' => 'edit', $brigada->id]);
}
$this->set('brigada', $brigada);
}
}
Before saving I find that the value of $brigada->photo and $brigada->dir are null, but values don't save. I have several possibilities that want to explore but my knowledge of PHP is a hindrance:
I may be doing updates wrong. Link
I may need to use the deleteCallback which is documented here, but I don't know how to do it. I figured that it would be with $this->Brigadas->deleteCallback() or something similar, but I'd like to understand an example first, which is why I'm asking. I found no use of these callbacks in any example on the web, and the documentation on events is still a bit esoteric for me.
Here is how BrigadasTable.php is setup to upload files:
// http://josediazgonzalez.com/2015/12/05/uploading-files-and-images/
$this->addBehavior('Josegonzalez/Upload.Upload', [
'photo' => [
'fields' => [
'dir' => 'dir',
'size' => 'photo_size', // defaults to `size`
'type' => 'photo_type', // defaults to `type`
],
'nameCallback' => function ($table, $entity, $data, $field, $settings) {
if ($entity->gvCode){
$array = explode(".", $data['name']);
return strtolower($entity->gvCode) . '_' . date("Ymd-hisa") . '.jpg';
} else{
$array = explode(".", $data['name']);
$newArray = array_pop($array);
return strtolower(join('_', $array)) . '_' . date("Ymd-hisa") . '.jpg';
}
},
'transformer' => function ($table, $entity, $data, $field, $settings) {
$extension = pathinfo($data['name'], PATHINFO_EXTENSION);
// Store the thumbnail in a temporary file
$tmp = tempnam(sys_get_temp_dir(), 'upload') . '.' . $extension;
// Use the Imagine library to DO THE THING
$size = new \Imagine\Image\Box(640, 640);
$mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$imagine = new \Imagine\Gd\Imagine();
// Save that modified file to our temp file
$imagine->open($data['tmp_name'])
->thumbnail($size, $mode)
->save($tmp);
$filenameTmp = explode('.', $data['name']);
array_pop($filenameTmp);
$filenameTmp = join('_', $filenameTmp) . '.jpg';
// return debug($filenameTmp);
// Now return the original *and* the thumbnail
return [
$data['tmp_name'] => $filenameTmp,
$tmp => 'thumbnail-' . $filenameTmp,
];
},
'deleteCallback' => function ($path, $entity, $field, $settings) {
// When deleting the entity, both the original and the thumbnail will be removed
// when keepFilesOnDelete is set to false
$entity->{$field} = null;
return [
$path . $entity->{$field},
$path . 'thumbnail-' . $entity->{$field}
];
},
'keepFilesOnDelete' => false
]
]);
Thank you!
You can run an update query straight, instead of fetching the record, setting values and saving it.
$query = $this->Brigadas->query();
$query->update()
->set([
'dir' => null,
'photo' => null,
])
->where(<condition>)
->execute();
Incase any of your columns are json,
$query = $this->Brigadas->query();
$query->update()
->set([
'dir = null',
'photo' => null,
])
->where(<condition>)
->execute();
I am facing this error while uploading an image with a title and description text to DB in PHP Laravel. I am using the same code for other webpage there it is working properly but the same code is not working here.
Below is a function code inside my controller, where I am passing tile, description, img and input names from a form.
public function submitFanfic(Request $request){
$user_id = session('userid');
$name = $_FILES['img']['name'];
$tem_name = $_FILES['img']['tmp_name'];
$dir = 'public/uploads/fanfic/';
$dir1 = $dir.$name;
move_uploaded_file($tem_name, $dir1);
$data = array(
'fanfic_title' => $request['title'],
'fanfic_desc' => $request['description'],
'img' => $name,
'user_id' => $user_id
);
DB::table('fanfic')->insert($data);
Session::flash('message', 'Fanfic Submitted Successfully');
return redirect('/author/write_fanfic');
}
I tried again and again and this code (specifically for image insertion into DB) worked!!
public function submitFanfic(Request $request){
$user_id = session('userid');
$imageName = $request->file('img');
if($imageName!==null){
// get the extension
$extension = $imageName->getClientOriginalExtension();
// create a new file name
$new_name = date( 'Y-m-d' ) . '-' . str_random( 10 ) . '.' . $extension;
// move file to public/images/new and use $new_name
$imageName->move( public_path('uploads/fanfic'), $new_name);
}
$fanfic_data = array(
'fanfic_title' => $request['title'],
'fanfic_desc' => $request['description'],
'img' => $new_name,
'user_id' => $user_id
);
DB::Table('fanfic')->insert($fanfic_data);
Session::flash('message', 'Fanfic Submitted Successfully');
I'm pretty new to Laravel, thus I'm trying to learn some of the basics. I have managed to create a CRUD with file upload. What I did was I created a resource controller. My store method:
public function store(Request $request) {
$this->validate($request, [
'name' => 'required',
'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
'boat_type' => 'required',
'rooms' => 'required',
'price_per_hour' => 'required',
'price' => 'required',
]);
$boat = new Boat($request->input()) ;
if($file = $request->hasFile('avatar')) {
$file = $request->file('avatar') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/img/boats/avatars/' ;
$file->move($destinationPath,$fileName);
$boat->avatar = $fileName ;
}
$boat->save() ;
return redirect()->route('management.index')
->with('success','New Boat Successfully Added!');
}
This method works perfectly fine, with this I am able to upload and store the details to my database and am able to manipulate it in my view.
But when I try to use the UPDATE method I have the exact code.. yet when I try to update my post everything can be updated except my avatar variable. it updates it but it stores it in a strange format. Here is my UPDATE method
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'boat_type' => 'required',
'rooms' => 'required',
'price_per_hour' => 'required',
'price' => 'required',
]);
$boat = Boat::find($id);
if($file = $request->hasFile('avatar')) {
$file = $request->file('avatar') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/img/boats/avatars/' ;
$file->move($destinationPath,$fileName);
$boat->avatar = $fileName ;
}
$boat->save() ;
$boat_update = $request->all();
$boat->update($boat_update);
$request->session()->flash('alert-success', 'Boat Successfully Updated!');
return redirect('/management');
}
When I edit the avatar variable it stores it in /img/boats/avatars/C:\xampp\tmp\phpFA50.tmp
I'm not really sure what is wrong. Any help will be greatly appreciated.
$boat->save() ; you don't need to save before update -> remove it
$boat_update = $request->all(); -> Your filename is NOT in there
$boat->update($boat_update); Are all the fields $fillable? If yes you need to add the new filename to that array
Found the solution, it was pretty much a logic error as I was simply saving the file name then overwriting it with the $request->all()
The correct solution would be this:
$boat = Boat::find($id);
$boat->fill($request->except('avatar'));
if($file = $request->hasFile('avatar')) {
$file = $request->file('avatar') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/img/boats/avatars/' ;
$file->move($destinationPath,$fileName);
$boat->avatar = $fileName ;
}
$boat->save();
$request->session()->flash('alert-success', 'Boat Successfully Updated!');
return redirect('/management');`
I'm creating an Image Editing order system, where a user can upload multiple images by DropZone & Laravel. I want to implement after successful image upload image information save to database & send User an email notification. Then redirect to another page with session message. My code sends more than 1 email every time when saving data to the database. But I need to send an email when all image data successfully saved to the database. Here my code:
$order = Order::find($request->input('order_id'));
$order->images()->create([
'order_id' => $request->input('order_id'),
'file_name' => $filename,
'file_size' => $file->getClientSize(),
'file_path' => $path . '/' . $filename,
]);
// When all file details saved to database send Single Notification mail
$data = array(
'fullname' => $order->user->fullname,
'email' => $order->user->email,
'order_number' => $order->order_number
);
Mail::send('emails.order-submit', $data, function($message) use ($data) {
$message->from('test#gmail.com');
$message->to($data['email']);
$message->subject('Order Submit');
});
Here is my Full Controller Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Model\Order;
use Session;
use Mail;
use Illuminate\Support\Facades\Auth;
class Images1Controller extends Controller
{
public function __construct() {
$this->middleware('auth');
}
public function doImageUpload(Request $request) {
//get the file from the post request
$file = $request->file('file');
//set the file name
$filename = $file->getClientOriginalName();
//move the file to correct location
$order_number = $request->input('oid');
$username = Auth::user()->username;
$path = 'orders/'. $username .'/' . $order_number;
if(!file_exists($path)){
mkdir($path, 0777, true);
}
$file->move($path, $filename);
//save the multiple/single file details to database
$order = Order::find($request->input('order_id'));
$order->images()->create([
'order_id' => $request->input('order_id'),
'file_name' => $filename,
'file_size' => $file->getClientSize(),
'file_mime' => $file->getClientMimeType(),
'file_path' => $path . '/' . $filename,
]);
Session::put('success','Your order has been submitted successfully.');
$data = array(
'fullname' => $order->user->fullname,
'email' => $order->user->email,
'order_number' => $order->order_number
);
Mail::send('emails.order-submit', $data, function($message) use ($data) {
$message->from('test#gmail.com');
$message->to($data['email']);
$message->subject('Order Submit');
});
}
}
DropZone Configuration Code:
Dropzone.options.uploadImages = {
autoProcessQueue: false,
maxFilesize: 2048,
uploadMultiple: false,
parallelUploads: 100,
acceptedFiles: 'image/*',
addRemoveLinks: true,
dictRemoveFile: 'Remove',
init: function() {
var submitButton = document.querySelector("#submit-images")
addImages = this; // closure
submitButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
addImages.processQueue(); // Tell Dropzone to process all queued files.
});
this.on("addedfile", function(file) {
// Show submit button here and/or inform user to click it.
});
this.on("success", function() {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
window.location.href = 'http://localhost:8000/user/orders/manage/';
}
});
}
};
Try this:
$order = Order::find($request->input('order_id'));
foreach( $request-order_id as $key=>$val){
$order->images()->create([
'order_id' => $request->input('order_id'),
'file_name' => $filename,
'file_size' => $file->getClientSize(),
'file_mime' => $file->getClientMimeType(),
'file_path' => $path . '/' . $filename,
]);
}
// When all file details saved to database send Single Notification mail
$data = array(
'fullname' => $order->user->fullname,
'email' => $order->user->email,
'order_number' => $order->order_number
);
Mail::send('emails.order-submit', $data, function($message) use ($data) {
$message->from('test#gmail.com');
$message->to($data['email']);
$message->subject('Order Submit');
});
FORM input should be like this
<input type="file" name="images[]" multiple />
And code for the doImageUpload method is
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach($files as $file) {
//set the file name
$filename = $file->getClientOriginalName();
//move the file to correct location
$order_number = $request->input('oid');
$username = Auth::user()->username;
$path = 'orders/'. $username .'/' . $order_number;
if(!file_exists($path)){
mkdir($path, 0777, true);
}
$file->move($path, $filename);
//save the multiple/single file details to database
$order = Order::find($request->input('order_id'));
$order->images()->create([
'order_id' => $request->input('order_id'),
'file_name' => $filename,
'file_size' => $file->getClientSize(),
'file_mime' => $file->getClientMimeType(),
'file_path' => $path . '/' . $filename,
]);
}
Session::put('success','Your order has been submitted successfully.');
$data = array(
'fullname' => $order->user->fullname,
'email' => $order->user->email,
'order_number' => $order->order_number
);
Mail::send('emails.order-submit', $data, function($message) use ($data) {
$message->from('test#gmail.com');
$message->to($data['email']);
$message->subject('Order Submit');
});
}
Solution is DropZone send single request instead of multiple request if
uploadMultiple: true, on DropZone Configuration. Now need update controller code as :
foreach($file as $key => $value) {
//save the multiple/single file details to database
$order->images()->create([
'order_id' => $request->input('order_id'),
'file_name' => $file[$key]->getClientOriginalName(),
'file_size' => $file[$key]->getClientSize(),
'file_mime' => $file[$key]->getClientMimeType(),
'file_path' => $path,
]);
//Move Files to destination path
$file[$key]-> move($path, $file[$key]->getClientOriginalName());
}
Here is updated Full Upload Method:
public function doImageUpload(Request $request) {
//get the file from the post request
$file = $request->file('file');
//move the file to correct location
$order = Order::find($request->input('order_id'));
$order_number = $order->order_number;
$now = Carbon\Carbon::now();
$year = date('Y', strtotime($now));
$month = date('M', strtotime($now));
$datetime = date('Ymd', strtotime($now));
$username = Auth::user()->username;
// public/orders/year/month/date/username/order-number
$path = 'orders/' . $year . '/' . $month . '/' . $datetime .'/' . $username . '/' . $order_number;
foreach($file as $key => $value) {
//save the multiple/single file details to database
$order->images()->create([
'order_id' => $request->input('order_id'),
'file_name' => $file[$key]->getClientOriginalName(),
'file_size' => $file[$key]->getClientSize(),
'file_mime' => $file[$key]->getClientMimeType(),
'file_path' => $path,
]);
//Move Files to destination path
$file[$key]-> move($path, $file[$key]->getClientOriginalName());
}
// Send Email Notification to User & Admin
$time = Carbon\Carbon::now();
Mail::to($order->user)->later($time,new PlaceOrder($order));
Mail::to('test#gmail.com')->later($time,new NewOrder($order));
Session::put('success','Your Order Submitted Success.');
return $order;
}
Here is updated Full DropZone Configuration:
Dropzone.options.uploadImages = {
autoProcessQueue: false,
maxFilesize: 2048,
uploadMultiple: true,
parallelUploads: 100,
acceptedFiles: 'image/*',
addRemoveLinks: true,
dictRemoveFile: 'Remove',
init: function() {
var submitButton = document.querySelector("#submit-images")
addImages = this; // closure
submitButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
addImages.processQueue(); // Tell Dropzone to process all queued files.
});
this.on("addedfile", function(file) {
// Show submit button here and/or inform user to click it.
});
this.on("success", function() {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
window.location.href = 'http://localhost:8000/user/orders/manage/';
}
});
}
};
I am trying to create event with picture, but when i upload picture to facebook it throws me an error (#324) Missing or invalid image file
this is the function to upload picture.
public function uploadFacebookEventPicture($fullPath, $eventId) {
$mainImage = '#' . $fullPath;
$imgData = array(
'picture' => $mainImage
);
try {
$data = $this->facebook->api('/'.$eventId, 'post', $imgData);
return $data;
} catch (FacebookApiException $e) {
error_log('Failed to attach picture to event. Exception: ' . $e->getMessage());
}
return null;
}
the par of code i use after form post
if ($file[$name]['error'] == 0) {
$fileName = $file[$name]['name'];
$fileInfo = pathinfo($fileName);
$newFileName = md5($fileName . microtime()) . '.' . $fileInfo['extension'];
$fullPath = $this->config->applications->uploadPath . $newFileName;
$form->$name->addFilter('Rename', $fullPath);
if ($form->$name->receive()) {
$resize = new SimpleImage();
$resize->load($fullPath);
$resize->resizeToWidth($this->config->applications->resize->width);
$resize->save($fullPath);
// Gathering data for saving files information
$fileInfo = array(
'name' => $newFileName,
'type' => FileTypes::IMAGE,
'description' => 'Application: Uploaded from Events form in back-end',
);
$fileId = $dbFiles->save($fileInfo);
$eventFileData = array(
'event_id' => $eventId,
'file_id' => $fileId,
'main_image' => ($name == 'mainImage') ? 1 : 0
);
$dbEventFiles->save($eventFileData);
if ($name === 'mainImage') {
$success = **$this->uploadFacebookEventPicture($fullPath, $eventData['fb_event_id']**);
}
}
}
facebook object is created with upload file true
$facebook = new Facebook(array(
'appId' => $config->facebook->appId,
'secret' => $config->facebook->secret,
'fileUpload' => true
));
According to Facebook bug tracker, this bug has been fixed:
Bug tracker post
Status changed to Fixed
Code above works fine for uploading facebook event picture.