How can i store actually path in database and how can i fetch image in API?
This is output of API in postman
This is database which show store path of image but its wrong..
public function store(Request $request)
{
$event = $request->all();
if ($request->hasFile('file')) {
$destinationPath = public_path().'/public/img/';
$file = $request->file;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
$input['e_image'] = $fileName;
}
// $return['success'] = true,
// $return['data'] = $event,
// $return['msg'] = "this is message ";
$success['status'] = true;
$success['data'] = [$event];
$success['message'] ="Event created successfully!";
// $success['event'] = $event;
return response()->json($success);
}
$file = new YOURMODELNAME(); please enter your model name in this line of code
public function store(Request $request)
{
$input = $request->all();
$rules = array(
'e_image' => 'required|mimes:jpeg,png,jpg,doc,docx,pdf,mp4,mov,ogg,qt',
'e_group' => required,
'e_invite'=>required,
);
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
$arr = array("status" => 400, "message" => $validator->errors()->first(), "data" => array());
} else {
try {
$file = $request->file('e_image');
$input['e_image'] = time() . '.' . $file->getClientOriginalExtension();
$destinationPath = public_path('/img/');
$file->move($destinationPath, $input['e_image']);
$file = new YOURMODELNAME();
$file->e_image = $input['e_image'];
$file->e_group = $input['e_group'];
$file->e_invite = $input['e_invite'];
$file->save();
$file->e_image = url('public/img/' . $file->e_image);
$arr = array("status" => 200, "message" => "file upload Successfully", "data" => $file);
} catch (\Exception $ex) {
if (isset($ex->errorInfo[2])) {
$msg = $ex->errorInfo[2];
} else {
$msg = $ex->getMessage();
}
$arr = array("status" => 400, "message" => $msg, "data" => array());
}
}
return \Response::json($arr);
}
please try this one and store image in proper project directory with unique image name .
$img = $request->profile_image;
$old_path = public_path() . "/public/img/";
$image_parts = explode(";base64,", $img);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$filename = uniqid() . '.png';
$file = $old_path . $filename;
file_put_contents($file, $image_base64);
if (file_exists(public_path('/public/img/' . $filename))) {
//move image
$new_path = public_path() . "/public/img/newimages/";
if (!is_dir($new_path)) {
mkdir($new_path, 0777, TRUE);
}
$move = File::move($old_path . $filename, $new_path . $filename);
}
//upload image at database
$modalObj = new table();
$modalObj->updateById(\Session::get('table')->id, [
'profile_photo' => $filename,
]);
return response()->json(['code' => '1', 'message' => 'Image Uploaded successfully!!!', 'data' => ['imageName' => url('/public/img/newimages/' . $filename)]]);
Related
Laravel 8 cannot upload .apk files. I get the following error.
[error:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
1
if ($request->hasFile('file_name')) {
$filenameWithExt = $request->file('file_name')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('file_name')->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
$fileNameToStore = $filenameWithExt;
$path = $request->file('file_name')->storeAs('public/apkfile/', $fileNameToStore);
$apkstore = Apkfile::find($apk->id);
$apkstore->file_name = $fileNameToStore;
$apkstore->save();
}
}
if($request->file('file_name')){
$apk = Apkfile::create([
'apk_name' => $request->apk_name,
'package_name' => $request->package_name,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
]);
$filenameWithExt = $request->file('file_name')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('file_name')->getClientOriginalExtension();
$check=in_array($extension,$allowedfileExtension);
if ($check) {
//$fileNameToStore = $filename. '.' . $extension;
$fileNameToStore = $filenameWithExt;
$path = $request->file('file_name')->storeAs('public/apkfile/', $fileNameToStore);
$apkstore = Apkfile::find($apk->id);
$apkstore->file_name = $fileNameToStore;
$apkstore->save();
return redirect()->route('admin.apk.index')->with('success', 'Apk Uploaded successfully');
}
else{
return redirect()->route('admin.apk.index')->with('error', 'not upload unsuccessfully');
}
I have problem with file upload. Now I have something like this (part of Controller):
if($request->has('photos')) {
foreach ($request->photos as $photo) {
$filename = $photo->getClientOriginalName();
$tmp_name = $filename;
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$uniq_no = 0;
while (file_exists($filename)) {
$tmp_name = $name .'_'. $uniq_no . $ext;
$uniq_no++;
}
$photo->storeAs('public/photos/',$tmp_name);
Photo::create([
'page_id' => $page->id,
'filename' => $tmp_name
]);
}
}
but saves to the database without adding a unique number: filename_0, filename_1 etc. It just saves the value of $tmp_name.
What am I doing wrong?
I did something like this:
if($request->has('photos')) {
foreach ($request->photos as $photo) {
$file = $photo->getClientOriginalName();
$filename = pathinfo($file, PATHINFO_FILENAME).'_'.Str::random(6);
$extension = pathinfo($file, PATHINFO_EXTENSION);
$fullfilename = $filename .'.'. $extension;
$photo->storeAs('public/photos/',$fullfilename);
Photo::create([
'page_id' => $page->id,
'filename' => $fullfilename
]);
}
}
whenever I uploaded an image in laravel, the image is upload to the database but after database uploading, my image didn't save that image in my root folder,
here is my upload code:
public function store(Request $request)
{
$records = $request->all();
if ($records != '') {
if ($request->session()->has('is_user_logged')) {
$UserPostModel = new UserPostModel;
$UserPostModel->uid = $request->session()->get('uid');
$UserPostModel->uname = $request->session()->get('name');
$UserPostModel->msg = $request->input('status');
$UserPostModel->eid = $request->input('event');
if ($request->hasFile('image')) {
if ($request->file('image')->isValid()) {
$fileName = $request->file('image')->getClientOriginalName();
$fileName = time() . "_" . $fileName;
$request->file = move_uploaded_file('uploads',$fileName);
$UserPostModel->image = $fileName;
}
}
$UserPostModel->save();
return redirect('uprofile')->with('message', 'Seccessfully Post !');
} else {
return redirect('login');
}
} else {
return redirect('/uprofile')->with('message', 'Please select image!');
}
}
Use store method and pass the driver as the second argument
$path = $request->file('image')->store($store_path, 'public');
Please replace this code with your image upload condition.
if ($file = $request->file('image')) {
$name = time() . $file->getClientOriginalName();
$file->move('uploads', $name);
$UserPostModel->image = $name;
}
$UserPostModel -> save();
I can run this code via cmd. And my question is how can I run this command to my laravel project locally and also to my live server?
ffmpeg -i input1.webm -i input2.webm output.mp3
Thanks in advance.
you install the ffmpeg .exe file on your system.
Then you use that code in your application so,first you need to install the application of ffmpeg
public function store(Request $request) {
$rules = [
'title' => 'required',
'description' => 'required',
'meta_title' => 'required',
'category_id' => 'required',
'video_file' => 'required',
'tags' => 'required',
];
$messages = [
'category_id.required' => 'Category field required.',
'tags.required' => 'Tag field required',
];
$validator = Validator::make($request->all(),$rules, $messages);
$validator->sometimes('file', 'nullable|mimes:csv,xlsx|max:1024000', function ($request) {
$messages = ['file.mimes'=>'file type must be csv or xlsx.'];
return ($request->category_id == 2 || $request->category_id == 4);
});
$validator->sometimes('file', 'nullable|mimes:pdf|max:1024000', function ($request) {
$messages = ['file.mimes'=>'file type must be pdf.'];
return ($request->category_id == 1);
});
if($validator->fails()) {
return response()->json(['error'=>$validator->errors(),'status'=>false]);
}else {
DB::beginTransaction();
try {
$formData = new Video();
$formData->title = $request->title;
$formData->user_id = Auth::id();
$formData->description = $request->description;
$formData->upload_date = Carbon::now();
//$formData->meta_title = implode(",",$request->meta_title);
$formData->meta_description =isset($formData->meta_description)?implode(",", $request->meta_description):'';
//$formData->tags = implode(",",$request->tags);
$formData->category_id = $request->category_id[0];
if($request->hasFile('image_file')) {
$uploadedFile = $request->file('image_file');
$filename = time().$uploadedFile->getClientOriginalName();
$imagePath = Storage::disk('public')->putFileAs(
'images',
$uploadedFile,
$filename
);
$formData->image_file = $imagePath;
}
if($request->hasFile('video_file')) {
$uploadedFile = $request->file('video_file');
$filename = trim(time().$uploadedFile->getClientOriginalName());
$removeSpaceFromFile = preg_replace('/[^A-Za-z0-9\-]/', '', $filename);
$filePath = Storage::disk('public')->putFileAs(
'videos',
$uploadedFile,
$removeSpaceFromFile
);
$formData->video_file = $filePath;
$video_id = DB::getPdo()->lastInsertId();
$filefullPath = asset('storage').'/'.$filePath;
$getOutputFilePath = Mp3AndTumbnails::where('id',1)->first();
$outputMp3File = $getOutputFilePath->mp3_output_path;
$outputImageFile = $getOutputFilePath->thumbnails_path;
// $mp3Filename = $video_id.'.mp3';
// $imageFileName = $video_id;
$mp3Filename = preg_replace('/[^A-Za-z0-9\-]/', '_',$request->title).'.mp3';
$imageFileName = preg_replace('/[^A-Za-z0-9\-]/', '_',$request->title);
$output = shell_exec('ffmpeg -i '. $filefullPath.' -vn -ar 44100 -ac 2 -ab 192 -f mp3 '. $outputMp3File.'/'.$mp3Filename);
$imageOutput = shell_exec('ffmpeg -i '.$filefullPath.' -ss 00:00:10 -vframes 1 -s 370x220 '.$outputImageFile.'/'.$imageFileName.'.jpg -hide_banner');
$formData->mp3_file = $mp3Filename;
$formData->image_file = 'images/'.$imageFileName.'.jpg';
$dur = shell_exec("ffmpeg -i ".$filefullPath." 2>&1");
preg_match("/Duration: (.{2}):(.{2}):(.{2})/", $dur, $duration);
if(isset($duration[1])) {
$hours = $duration[1];
$minutes = $duration[2];
$seconds = $duration[3];
$video_length = $hours.':'.$minutes.':'.$seconds;
$formData->video_length = $video_length;
}
}
if($request->hasFile('file')) {
$lyricsFile = $request->file('file');
$categoryInfo = Category::where('id',$request->category_id[0])->first();
$filename = time().$lyricsFile->getClientOriginalName();
$lyricsFile->move(public_path("download".'/'.$categoryInfo->name), $filename);
$path = $filename;
$formData->lyrics_file = $path;
}
$formData->save();
foreach ($request->category_id as $key => $value) {
$category = new VideoCategoryUpload();
$category->video_id = $formData->id;
$category->category_id = $value;
$category->save();
}
$updateEncodeVideoId = Video::where('id',$formData->id)
->update(['base64_encode_video_id'=>base64_encode($formData->id)]);
foreach ($request->tags as $key => $value) {
$tagData = new TagModel();
$tagData->user_id = Auth::id();
$tagData->video_id = $formData->id;
$tagData->name = $value;
$tagData->slug_name = $value;
$tagData->save();
}
foreach ($request->meta_title as $key => $value) {
$metaTitleData = new MetaTitleModel();
$metaTitleData->user_id = Auth::id();
$metaTitleData->video_id = $formData->id;
$metaTitleData->title_name = $value;
$metaTitleData->title_slug_name = $value;
$metaTitleData->save();
}
DB::commit();
return response()->json(['status'=>true,'msg'=>'File uploaded successfully !!.']);
}catch(\Exception $e) {
DB::rollback();
return response()->json(['status'=>'exception','msg'=>'Something Went Wrong !!.']);
}
}
}
its working but how to resize image in it
public function store(Request $request)
{
$input = $request->all();
$image = Input::file('image');
if (isset($image)) {
$directory = public_path() . '/uploads/programs';
$medium_size = public_path() . '/uploads/programs/100X100/';
$thumb_nails = public_path() . '/uploads/programs/100X100/';
if (!file_exists($directory)) File::makeDirectory($directory, 0777, true, true);
$filename = sha1(time() . time()) . ".png";
$filename = $image->getClientOriginalName();
$filename = str_random(40) . "$filename";
$upload_success = $image->move($directory, $filename);
$input['image'] = $filename;
}
product::create($input);
return redirect('home');
}