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');
}
Related
my model
public function saveProduct(
$name,
$cat_id,
$user_id,
$description,
$status
) {
$post_image = '';
if (array_key_exists('post_image', $_FILES)) {
$config = [];
$config['upload_path'] = './assets/uploads/products';
$config['allowed_types'] = 'gif|svg|jpg|png|jpeg';
$config['max_size'] = '2048';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('post_image')) {
echo $this->upload->display_errors();
} else {
$post_image = $_FILES['post_image']['name'];
}
}
$data = [
'name' => $name,
'user_id' => $user_id,
'cat_id' => $cat_id,
'description' => $description,
'status' => 'active'
];
if ($post_image) {
$data['post_image'] = $post_image;
}
$this->db->insert('p0_products', $data);
return true;
}
it is changing file name to encryption in folder but in mysql i'am getting file name same as old name with unchanged on non-encrypted format
It's because you're taking from $_FILES veriable. You should take from
$this->upload->data()
So how?
$fileData = $this->upload->data();
This will return
file_name
file_type
file_path
etc.
$fileName = $fileData['file_name']
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
]);
}
}
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 !!.']);
}
}
}
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)]]);
I am currently beginning to learn CodeIgniter. There is this site that I've been working on.
In this site, users can upload PDF files but they are only allowed to view their uploaded files in JPG format. The question is, how can I convert the PDF file into JPG on the time of upload and store JPG format instead of PDF.
here is the code of my CONTROLLER
public function upload()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$data['permission'] = $session_data['permission'];
if($data['permission']=='Super Admin' || $data['permission']=='Admin'){
$this->load->view('header');
$this->load->view('upload_form', array('error' => ' ' ));
}
}
else
{
redirect('login', 'refresh');
}
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'pdf';
$config['max_size'] = '10000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('header');
$this->load->view('upload_form', array('error' => ' ' ));
}
else
{
$data = array('upload_data' => $this->upload->data());
$upload_data = $this->upload->data();
$session_data = $this->session->userdata('logged_in');
$first = $session_data['firstname'];
$last = $session_data['lastname'];
$dept = $session_data['department'];
$uploader = $first." ".$last;
$name = $upload_data['file_name'];
$path = $upload_data['file_path'];
$this->db->query("INSERT INTO tbl_uploaded
(`uploaded_id`, `name`, `path`,`department`,`uploader`)
VALUES ('','".$name."',
'". $path."','".$dept."','".$uploader."')");
redirect('csfi','refresh');
}
}
I've already read about Imagick but I don't know how to use it in CodeIgniter. Can you give me some tutorials and examples or a much easier way to convert PDF to JPG in CodeIgniter?
Thank you in advance guys.
$config = array();
$config['allowed_types'] = 'pdf';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
// Image manipulation library
$this->load->library('image_lib');
foreach ($notes['name'] as $key => $note)
{
$_FILES['notes']['name'] = $notes['name'][$key];
$_FILES['notes']['type'] = $notes['type'][$key];
$_FILES['notes']['tmp_name'] = $notes['tmp_name'][$key];
$_FILES['notes']['error'] = $notes['error'][$key];
$_FILES['notes']['size'] = $notes['size'][$key];
$extension = pathinfo($_FILES['notes']['name'], PATHINFO_EXTENSION);
$unique_no = uniqid(rand(), true);
$filename[$key] = $unique_no.'.'.$extension; // with ex
$filename2[$key] = $unique_no; // without ex
$target_path = "notes_files/";
if (!is_dir($target_path))
{
mkdir('./'.$target_path, 0777, true);
}
$config['file_name'] = $filename[$key];
$config['upload_path'] = './'.$target_path;
$this->upload->initialize($config);
if (! $this->upload->do_upload('notes'))
{
return array('error' => $this->upload->display_errors());
}
// converting pdf to images with imagick
$im = new Imagick();
$im->setResolution(160,220);
$ig = 0;
while(true)
{
try {
$im->readimage($config['upload_path'].$config['file_name']."[$ig]");
} catch (Exception $e) {
$ig = -1;
}
if($ig === -1) break;
$im->setImageBackgroundColor('white');
$im->setImageAlphaChannel(imagick::ALPHACHANNEL_REMOVE);
$im->mergeImageLayers(imagick::LAYERMETHOD_FLATTEN);
$im->setImageFormat('jpg');
$image_name = $filename2[$key]."_$ig".'.jpg';
$imageprops = $im->getImageGeometry();
$im->writeImage($config['upload_path'] .$image_name);
$im->clear();
$im->destroy();
// change file permission for file manipulation
chmod($config['upload_path'].$image_name, 0777); // CHMOD file
// add watermark to image
$img_manip = array();
$img_manip = array(
'image_library' => 'gd2',
'wm_type' => 'overlay',
'wm_overlay_path' => FCPATH . '/uploads/institutes/'.$institute_logo, // path to watermark image
'wm_x_transp' => '10',
'wm_y_transp' => '10',
'wm_opacity' => '10',
'wm_vrt_alignment' => 'middle',
'wm_hor_alignment' => 'center',
'source_image' => $config['upload_path'].$image_name
);
$this->image_lib->initialize($img_manip);
$this->image_lib->watermark();
ImageJPEG(ImageCreateFromString(file_get_contents($config['upload_path'].$image_name)), $config['upload_path'].$image_name, );
$ig++;
}
// unlink the original pdf file
chmod($config['upload_path'].$config['file_name'], 0777); // CHMOD file
unlink($config['upload_path'].$config['file_name']); // remove file
}
// echo '<p>Success</p>';exit;
die(json_encode(array(
'data' => 'Success',
'status' => 'success'
)));
Try this, you can upload and convert multiple files using this.