The post created is to save the image and description to the DB but only the description gets saved.The request is being done via formData()..So currently trying via postman
$post = new Post;
$post->user_id = Auth::user()->id;
$post->desc = $request->desc;
//check if post has photo
If($request->hasFile('image')){
$imageName = time().'.'.$request->image->extension();
$request->image->move('storage/posts', $imageName);
$post->photo = $imageName ;
}
//mistake
$post->save();
$post->user;
return response()->json([
'success' => true,
'message' => 'posted',
'post' => $post
]);
1_check directory has permission 777
2_$request->file('image')->move("directory", "new file name");
if($request->file('image') !=null){
$request->file('image')->move("directory", "new file name")
}
Related
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?
I have a laravel project that has a image upload. I used image intervention library for uploading. The problem is i got a 500 error and saying Malformed UTF-8 characters, possibly incorrectly encoded. But when I look my directory for saving, the image was saved but the data was not saved to the database. Only the image was saved. Seems like the image save was successful but the request is not. What seems to be the problem?
Controller
public function store(Request $request)
{
$product = new Product;
$validator = \Validator::make($request->all(), [
'product_name' => 'required',
'barcode' => 'required|unique:products',
'price'=> 'required',
'category' => 'required',
'supplier' => 'required',
// 'image' => 'required|image64:jpeg,jpg,png'
]);
if ($validator->fails()) {
$errors = json_encode($validator->errors());
return response()->json([
'success' => false,
'message' => $errors
],422);
} else {
$product->barcode = $request->barcode;
$product->product_name = $request->product_name;
$product->price = $request->price;
$product->quantity = 0;
$product->category = $request->category;
$product->supplier_id = $request->supplier;
//image
$imageData = $request->image;
$fileName = time().'.'. explode('/', explode(':', substr($imageData, 0, strpos($imageData, ';'))) [1])[1];
$product->image = \Image::make($request->image)->save(public_path('img/').$fileName);
$product->save();
broadcast(new ProductsEvent(\Auth::user()->name, 'add', $product))->toOthers();
}
}
Vue component event when form is changed
onFileChange(e) {
let file = e.target.files[0];
console.log(file);
var reader = new FileReader();
reader.onloadend = (file)=>{this.image = reader.result}
reader.readAsDataURL(file);
},
It seems that problem is appearing in your $filename generation.
As long as you have the correct image saved the naming convention is all in your hands.
I'd recommend you to go with simpler approach like
$fileName = now()->timestamp . '_' . $imageData->name; and there would be no need for you to go fancy with the name of the file.
The value of the $imageData can not be predicted and all the operations you execute could lead to that problem.
The question has been already asked Laravel "Malformed UTF-8 characters, possibly incorrectly encoded", how to fix?
--- Edit ---
You can get the filename directly from your javascript as you do all the manipulation at that end so you could for example add this.name = file.name; to your sent data, then in your ajax you can send that data like so -
axios.post('/image/store',{
image: this.image,
imageName: this.name
}).then(response => {...});
in your backend $fileName = now()->timestamp . '_' . $request->imageName;
The problem was this line, I was saving the actual image object in the db.
$product->image = \Image::make($request->image)->save(public_path('img/').$fileName);
I changed it into
$imageData = $request->image;
$fileName = time().'.'. explode('/', explode(':', substr($imageData, 0, strpos($imageData, ';'))) [1])[1];
\Image::make($request->image)->save(public_path('img/').$fileName);
$product->image = $fileName;
$product->save();;
I am currently trying to delete an image when a user updates his/her post before publishing.
Everything works fine, the image is changed in the database and post page, but I want to delete the previous image.
Here is my controller
public function updatePost(Request $request){
$data = $request->all();
$postid = $request['id'];
$isExist = Post::where('id', $postid)->first();
if($isExist){
if ($request->hasFile('image')) {
$file = $request->File('image');
//Get filename with extension
$fileNameToStoreWithExt = $file[0]->getClientOriginalName();
//Get just filename
$filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
//Get just ext
$extension = $file[0]->getClientOriginalExtension();
//File to store
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
//Upload Image
$path = $file[0]->storeAs('image', $fileNameToStore);
$file[0]->move('storage/image', $fileNameToStore);
File::delete(public_path('storage/image'.$isExist['image']));
Post::where('id', $postid)->update([
'title' => $data['title'],
'category' => $data['category'],
'content' => $data['content'],
'image' => $path
]);
return response()->json([
'status'=>'200',
'response'=> 'successfully updated'
]);
}else{
Post::where('id', $postid)->update([
'title' => $data['title'],
'category' => $data['category'],
'content' => $data['content']
]);
return response()->json([
'status'=>'200',
'response'=> 'successfully updated'
]);
}
}else{
return response()->json([
'error'=> 'post does not exist'
]);
}
}
I used:
File::delete(public_path('storage/image'.$isExist['image']));
but it didn't do the job
my delete function
public function deletePost($id){
$post = Post::where('id',$id)->first();
// dd($post);
if(!$post){
return response()->json([
'status' => '500',
'error' => 'post not found'
]);
}
Storage::disk('public')->delete('/storage/image'. $post['image']);
Post::where('id', $id)->delete();
return response()->json([
'status'=> '200',
'response'=> 'Post successfully deleted'
]);
}
my storage path snapshot
use Illuminate\Support\Facades\Storage;
Storage::delete('file.jpg'); // delete file from default disk
Storage::delete(['file.jpg', 'file2.jpg']); // delete multiple files
Storage::disk('your_disk')->delete('file.jpg'); // delete file from specific disk e.g; s3, local etc
Please refer link https://laravel.com/docs/6.x/filesystem
If you look at laravel file-system documentation you will see there are multiple Disk laravel support. you can used Storage Facades to delete a file from Storage like this
use Illuminate\Support\Facades\Storage;
Storage::disk('local')->delete('folder_path/file_name.jpg');
path should be like this for public directory.
Storage::disk('local')->delete('public/image/'.$filename);
its easy to do an if statement and delete old image on updating! this code is an example edit it to your requirements.
if ($request->hasFile('file')) {
Storage::delete($myImage->file); // If $file is path to old image
$myImage->file= $request->file('file')->store('name-of-folder');
}
Another :
File::delete(public_path('images/'. $oldFilename));
see here : https://laracasts.com/discuss/channels/laravel/delete-old-image-from-public-folder-after-updating
You can use normal PHP delete file keyword #unlink
if (file_exists($image)) {
#unlink($image);
}
You can use File to delete file from specific path
$file= "image path here";
\File::delete($file);
Delete uploaded file from public dir
OR
You can use unlink for the same
$image_path = "image path here";
if (file_exists($image_path)) {
#unlink($image_path);
}
PHP -> unlink
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 using Laravel 5.3 and need to upload an xml file and then submit the contents to an api. The client wants it as 2 buttons/user functions where the user should first upload the file and then with a second click submit the contents.
The uploading is working fine and the xml reading and submitting to api is also working properly. I just can't get my upload controller to pass the filename over to the submitting controller. There is no need to store the filename for future use and the processes will follow each other - ie user will upload one file and submit, then upload next file and submit.
Any help would be highly appreciated
upload function:
public function handleUpload(Request $request)
{
$file = $request->file('file');
$allowedFileTypes = config('app.allowedFileTypes');
$rules = [
'file' => 'required|mimes:'.$allowedFileTypes
];
$this->validate($request, $rules);
$fileName = $file->getClientOriginalName();
$destinationPath = config('app.fileDestinationPath').'/'.$fileName;
$uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));
if($uploaded) {
$file_Name = ($_FILES['file']['name']);
}
return redirect()->to('/upload');
}
submit function:
public function vendorInvoice()
{
$fileName = $file_Name;
$destinationPath = storage_path('app/uploads/');
$xml = file_get_contents($destinationPath.$fileName);
$uri = "some uri";
try {
$client = new Client();
$request = new Request('POST', $uri, [
'Authorization' => '$username',
'ContractID' => '$id',
'content-type' => 'application/xml'
],
$xml);
$response = $client->send($request);
}
catch (RequestException $re) {
//Exception Handling
echo $re;
}
}