how to upload audio with a file in laravel? - php

making an api to upload multifile with an audio everything is working but audio file can't uploaded
and uploading with dd($request)->all
then it works
but while uploading with any condition its gives null value on every clientoriginalName ,extension,
how t fix this...
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use App\File;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Auth;
class FileController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'description' => 'nullable',
'file' => 'required|file|mimes:' . File::getAllExtensions() . '|max:' . File::getMaxSize(),
'Fileaudio' =>'nullable|mimes:audio/mpeg,mpga,mp3,wav,aac'
]);
//////////// All files //////////////////
$file = new File();
$title = $request->title;
$uploaded_file = $request->file('file');
$filename = $uploaded_file->getClientOriginalName();
$original_ext = $uploaded_file->getClientOriginalExtension();
$type = $file->getType($original_ext);
$filepath = $uploaded_file->storeAs('public/upload/files/',$filename);
$files = URL::asset('storage/upload/files/' . $filename);
$description = $request->description;
$user_id = Auth::user()->id;
/////////// Audio at null /////////////////
$Fileaudio = $request->file('audio');
$audioname = $Fileaudio->getClientOriginalName();
$audiopath =$Fileaudio->storeAs('public/upload/files/audio/', $audioname);
//return $audiopath;
dd($request->all());
}
}
and i am sending request to postman...

create a folder 'upload/files' inside storage/app/public , and /upload/files/audio
then run command : php artisan storage:link
this command will link your storage folder to public folder
update your code :
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use App\File;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
public function store(Request $request)
{
// validation
$this->validate($request, [
'title' => 'required',
'description' => 'nullable',
'file' => 'required|file|mimes:jpeg,jpg,png,gif|max:2048',
'audio' =>'nullable|file|mimes:audio/mpeg,mpga,mp3,wav,aac'
]);
// code for upload 'file'
if($request->hasFile('file')){
$uniqueid=uniqid();
$original_name=$request->file('file')->getClientOriginalName();
$size=$request->file('file')->getSize();
$extension=$request->file('file')->getClientOriginalExtension();
$name=Carbon::now()->format('Ymd').'_'.$uniqueid.'.'.$extension;
$imagepath=url('/storage/uploads/files/'.$name);
$path=$request->file('file')->storeAs('public/uploads/files/',$name);
}
// code for upload 'audio'
// handle multiple files
if(is_array($request->file('audio')))
{
$audios=array();
foreach($request->file('audio') as $file) {
$uniqueid=uniqid();
$original_name=$file->getClientOriginalName();
$size=$file->getSize();
$extension=$file->getClientOriginalExtension();
$filename=Carbon::now()->format('Ymd').'_'.$uniqueid.'.'.$extension;
$audiopath=url('/storage/upload/files/audio/'.$filename);
$path=$file->storeAs('/upload/files/audio',$filename);
array_push($audios,$audiopath);
}
$all_audios=implode(",",$audios);
}else{
// handle single file
if($request->hasFile('audio')){
$uniqueid=uniqid();
$original_name=$request->file('audio')->getClientOriginalName();
$size=$request->file('audio')->getSize();
$extension=$request->file('audio')->getClientOriginalExtension();
$filename=Carbon::now()->format('Ymd').'_'.$uniqueid.'.'.$extension;
$audiopath=url('/storage/upload/files/audio/'.$filename);
$path=$file->storeAs('public/upload/files/audio/',$filename);
$all_audios=$audiopath;
}
}
}
in your postman request :
add key : "file" for image file ,
"audio" for audio file

you can use these there sentences for upload any multipart
$file = $request->file;
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move('your-path', $filename);
and if you need to upload multi audios or images make sure your key on postman wrote like this
images[]
or
audios[]

Related

How to POST data on database using Postman with laravel 9

I try to POST data to database with "form-data" on "postman" with Laravel 9, and I try to return the data to JSON.
This is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\M_Barang;
class Utama extends Controller
{
public function index() {
return view('Utama');
}
public function store(Request $request) {
$this->validate($request, [
'file' => 'required|max:2048'
]);
$file = $request->file('file');
$nama_file = time()."_".$file->getClientOriginalName();
$tujuan_upload = 'data_file';
if ($file->move($tujuan_upload,$nama_file)) {
$data = M_Barang::create([
'nama_produk' => $request->nama_produk,
'harga' => $request->harga,
'gambar' => $nama_file
]);
$res['message'] = "succsess!";
$res['values'] = $data;
return response($res);
}
}
}
I get the following result:
This is my expected result:
You need to send data from raw section in JSON Format, and try to send your image in base64 format (because its very convenient way to store a image into file system via the API).
Example:{"profile_pic":"data:image/png;base64,iVBORw0KGgoAAAANSUh (base64 image string)"}
you can convert base64 image here https://www.base64-image.de/
and in Android and iOS has some libraries for converting image to base 64 while sending data to API
Welcome in Advance.
In Postman's headers section, you have to set Accept and content-type to application/json:
Image

Laravel 8 - Intervention/image - undefined type 'Image'

I am creating a controller that saves photos to the /storage/ folder. To protect myself from submitting a bunch of large photos and not to style their CSS, I wanted to resize them using the Intervention / image library. Unfortunately, despite following the installation instructions directly from the documentation, several uninstallations and reinstallations of the library do not work. When I use this code snippet:
Use Image;
I get an error saying:
Undefined type 'Image'
Following the instructions, I added the following to /config/app.php:
'providers' => [
...
Intervention\Image\ImageServiceProvider::class,
],
'aliases' => [
...
'Image' => Intervention\Image\Facades\Image::class,
...
],
Besides, I cleaned and reconfigured the cache and config, restarted the server, tried to use:
use Intervention\Image\ImageManagerStatic as Image;
But unfortunately that didn't help either.
What am I doing wrong?
You have to use the namespace below
use Intervention\Image\Facades\Image;
Then you can use like-
$image = $request->file('image');
$ext = $image->getClientOriginalExtension();
$img = Image::make($image)->resize(300, 200)->save('storage/folder/filename'.'.'.$ext);
Use Image facade directly
\Intervention\Image\Facades\Image::make(\File::get($file_address))
->fit($width, $height)
->save($path_for_saving);
You can fit or crop the image based on your needs.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
public function imageUploadPost(Request $request)
{
$photo = $request->file('image');
$imagename = time() . '.' . $photo->getClientOriginalExtension();
// Upload Crop Image...
$destinationPath = public_path('uploads/thumbnail_images');
if (!File::isDirectory($destinationPath)) {
File::makeDirectory($destinationPath, 0777, true, true);
}
$thumb_img = \Intervention\Image\Facades\Image::make($photo->getRealPath())->resize(100, 100);
$thumb_img->save($destinationPath . '/' . $imagename, 100); // Define Quality 100 (Optional)
echo '<pre>';
print_r("Upload Successfully. Store File : laravel_project/public/uploads & laravel_project/public/uploads/thumbnail_images");
}

Laravel 8: How To Use Intervention Image Library Properly

I want to use Intervention Image library for my Laravel project, so I just installed it via Composer and added this line of code to config/app.php:
Intervention\Image\ImageServiceProvider::class,
And also this line was added to aliases part:
'Image' => Intervention\Image\Facades\Image::class,
Now at my Controller I coded this:
class AdminController extends Controller
{
protected function uploadImages($file)
{
$year = Carbon::now()->year;
$imagePath = "/upload/images/{$year}/";
$filename = $file->getClientOriginalName();
$file = $file->move(public_path($imagePath), $filename);
$sizes = ["300","600","900"];
Image::make($file->getRealPath())->resize(300,null,function($constraint){
$constraint->aspectRatio();
})->save(public_path($imagePath . "300_" . $filename));
}
}
But as soon as I fill my form to check if it's work or not, this error message pops up:
Error
Class 'App\Http\Controllers\Admin\Image' not found
Which means this line:
Image::make($file->getRealPath())->resize(300,null,function($constraint){
So why it returns this error while I've included it already in my project ?!
If you know, please let me know... I would really appreciate that.
Thanks
On config/app.php you need to add :
$provides => [
Intervention\Image\ImageServiceProvider::class
],
And,
$aliases => [
'Image' => Intervention\Image\Facades\Image::class
]
Now you can call use Image; on the top on your controller :
use Image;
class AdminController extends Controller
{
// ...
}

Request file() is null in api Laravel

I have a route in my API right in Laravel for an iOS app that lets you upload images that I got form this tutorial https://www.codetutorial.io/laravel-5-file-upload-storage-download/
and when I tried to upload the file it turns null.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Fileentry;
use Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Response;
class FileEntryController extends Controller
{
public function add() {
$file = Request::file('filefield');
$extension = $file->getClientOriginalExtension();
Storage::disk('local')->put($file->getFilename().'.'.$extension, File::get($file));
$entry = new Fileentry();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
return redirect('fileentry');
}
}
Route:
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->post('fileentry/add',array(
'as' => 'addentry',
'uses' => 'App\Http\Controllers\FileEntryController#add'
));
}
the user doesn't interact with the web page is all through the app
Other information that maybe the cause of the problem is that i'm using Postman to upload the image to the laravel app (Method: POST, through the binary section).
Try using form-data method from postman and add a parameter as file type.
Keep in mind that the key of the parameter must be equal to the key you're trying to get in backend. In your case it is filefield
$file = Request::file('filefield');
In your html form add this attribute
enctype="multipart/form-data"

Class 'Storage' not found in lumen while using aws s3 instance for storage

I am using AWS s3 instance to store all my files . but it is showing class Storage not found.I have imported all the required namespaces and classes.
use Storage;
use Illuminate\Http\Request;
use Illuminate\Contracts\Filesystem\Filesystem;
function logic goes like this.
public function insertAdvertisement($input)
{
$advertisment = new AdvertisingBanner;
$image = $input['image'];
$imageName = "Banner" . time() . '.' . $input['image']->getClientOriginalExtension();
/*$input['image']->move(
base_path() . '/public/uploads/advertiseImages/', $imageName
);*/
$disk = \Storage::disk('s3');
$filePath ='/public/uploads/advertiseImages/'.$imageName;
$s3->put($filePath, file_get_contents($image), 'public');
$advertisment->title = $input['title'];
$advertisment->image = $imageName;
$advertisment->added_by = $input['added_by'];
$advertisment->save();
return $advertisment->save();
}
Lumen 5.2+ removed the global class alias for the Storage facade. Change your use statement to:
use Illuminate\Support\Facades\Storage;
And then in your code:
// no starting slash; rely on use statement
$disk = Storage::disk('s3');

Categories