How NOT to change file extension when uploading it? - laravel

In my Laravel project I need to upload mp3 files, However Laravel using mpga as a mime type to validate mp3 files type I found that in this answer.
$results = Validator::make($request->all(), [
"song" => "required|file|mimes:mpga|max:8192",
]);
I am okay with that but my problem is the file is stored with mpga extension, I know the reason behind this weird action from this answer.
How I store the file
// Upload the song
$filePath = $request->song->store("public/songs");
But I want to store the file with mp3 extension.

Without seeing your code, the best I can suggest is to use the putFileAs() method from the Storage class.
This method allows you to specify a file name when storing your file:
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
// Manually specify a file name:
Storage::putFileAs(
'folder',
new File('/path/to/uploaded-music.mp3'),
'stored-song-name.mp3'
);
See Laravel doc: https://laravel.com/docs/5.8/filesystem#storing-files
Edit: If you want to keep Laravel random file naming just like the putFile() method does, you can generate a random string and append your extension:
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
// Manually specify a file name:
Storage::putFileAs(
'folder',
new File('/path/to/uploaded-music.mp3'),
Str::random(40) . '.mp3'
);
If you look at Laravel source code, this is how putFile() does it to generate a random file name.

Lobsterbaz's answer works perfectly, and i also want to give alternative to that answer which will help you to keep your file's extension as it is.
Laravel changes mp3 file's extension as mpga after uploading, so here i will show you how to keep mp3 file's extension as it is after uploading, below code will help you to do it:
use Illuminate\Support\Str;
$path = $request->file('song')->storeAs(
'songs', Str::random(40).".mp3"
);
Congrats, Now your song will be stored as mp3, but be sure to upload mp3 files only and put validation of mimes for mp3 otherwise it can break the file.

Related

how get laravel file manager image thumbnail

I install the Laravel file manager package in my app. but already I cant use thumbnail images in the blog.
How can I get an image thumbnail of uploaded photos when I use Laravel file manager?
After much searching, I realized that such a function does not exist (at least until the time of writing this message).
I defined a function in the helper that returns the address of the thumbnail from the URL of the original image.
The reader should note that these definitions may differ based on the setting of parameters for another person.
function LMFThums($url)
{
$url2= str_replace(basename($url) , '', $url ) ;
$url2=$url2.'thumbs/'.basename($url);
return $url2 ;
}

Laravel 8: How can I convert base64 PDF to PDF file?

I am trying to save a pdf and other documents file like Docx and video in the database using a base64.
what I want to do is to revert the changes from base64 to the exact file. is it possible to do that? thank you and stay safe.
I know it is a duplicate question, but I cannot find any answer in laravel.
You can decode and then pass to Storage put method
Storage::disk('public')->put('file.pdf',base64_decode($base64encodedstring));
don't forget to import Storage facade
use Illuminate\Support\Facades\Storage;
$filename = 'upload/profile_pic/' . md5(uniqid(rand(), true)) . '_' . $input['document']['filename'];
file_put_contents($filename, base64_decode($input['document']['base64']));
$input['document'] = $filename;
Decode file and save the file in the public path, create upload folder in the public folder and save any file.

Get correct URL for uploaded files

I have a function in my platform for letting users upload their own icon images. Once they've uploaded them I save them using $request->icon->store('public/icons') and simply save the returned path, something like "public/icons/xa6y2am3e4cOdqQuLpvEhFSXDKwFMDOgggS2i67l.png".
I'm not really clear though on what's the correct way to show the icons. The URL for showing the icon in the above example is "/storage/icons/xa6y2am3e4cOdqQuLpvEhFSXDKwFMDOgggS2i67l.png", thus I need to replace "public" in the path with "storage", which makes me think I've done something wrong somewhere (I see no reason why the store() method should provide me with a path that's not correct).
I have done my symlinks as described in the documentation. Using the local storage. What am I missing?
This is how I handle my storage in one of my apps that includes blogs:
$storedImageName = $request->file('main_image')->store('blog_images', 'public');
The store method actually returns the stored file name along with the path. Here, I specify that my disk is public and that the folder inside public is blog_images. I store the result of that in $storedImageName.
Now, to save it in the database, I do not actually save the whole path, I save ONLY the image name. This is because, you may want to update your directory name in the future, or move it to another location, etc. You can get that like this:
$onlyImageName = basename($storedImageName);
basename() is PHP's function, has nothing to do with Laravel.
This way, I can render my images in my blade files like this:
<img ... src="{{ asset('/storage/blog_images/' . $blog->main_image) }}" />
asset() helper will provide you with path to your public directory, and then you just need to specify the rest of the path to your image.

How can I restrict accepted media types in the media field on Strapi

As far as I see there is only one type of media field which can hold every type of media (image, video, pdf etc.) Is there a way to restrict the media type, so that the field only accepts images and no other filetypes? Because when I allow the field to hold multiple files the array will hold images, video and files. I search for a solution how I can restrict the data types for this field.
You can deal with that by updating the upload function of the upload plugin.
Please for that you will have to check how the extensions folder work.
📚Documentation here: https://strapi.io/documentation/3.0.0-beta.x/concepts/concepts.html#extensions
And after you will have to find the path of the file you want to update.
It will be this one https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-upload/controllers/Upload.js
So you will have to create an empty file at the same path in the extension folder.
It will be ./extensions/upload/folder/Upload.js
module.exports = {
};
In this file you will have to create the function you want to update/override.
It will be this function https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-upload/controllers/Upload.js#L12
So you have to copy this function and past it in your extensions file.
When it's done you can modify the function as you want.
Here in the function https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-upload/controllers/Upload.js#L27 you can see the var files contain all your files, you can simply add your code to test the type of your files.

Why are images uploaded through the admin panel of my custom module, having the file name of Array?

Here is my BrandController.php
https://gist.github.com/a958926883b9e7cc68f7#file-brandcontroller-php-L53
I've gone through all my files of my custom module, and compared them to the one given from the custom module maker, and I couldn't find much differences.
Are you attempting to upload multiple files? If you're using multiple fileupload elements with the same name you'll get an array of items.
So when the following line is called,
//this way the name is saved in DB
$data['filename'] = $_FILES['filename']['name'];
It will have the value
["name"]=>array(2) {
[0]=>string(9)"file0.txt"
[1]=>string(9)"file1.txt"
}
you'll need to update the code to loop through each $_FILES['filename']['name'] and upload and save the files separately.
You may unknowingly uploaded multiple files. If you that is not your intention, you may check your in your HTML and check the name attribute of the tag. It must not be an array (like this).
<input type="file" name="my_files[]" />
If you only see Array() in your database, it means you are indeed uploading a multiple files. You can process them by using loops.
If you are really sure that you are uploading 1 image, you may follow #Palanikumar's suggestion. Use a print_r() and display the $_FILES and paste it here. IF you don't want to use that, You can use
json_encode($the-data-you-are-going-to-insert-to-the-database);
If you don't know where to put the print_r() function, you may put it after line 56 of this file.
https://gist.github.com/desbest/a958926883b9e7cc68f7#file-brandcontroller-php-L53
if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
print_r($_FILES);
die;
If saveAction() is being called inside an ajax function you need to log the ajax response. Assuming you are using jquery..
$ajaxResponse = $.POST({...});
console.log($ajaxResponse.responseText);
Then, you you can view it inside a browser's console. If nothing appears, you may use a non-async request
$ajaxResponse = $.POST({
// your options,
// your another option,
async: FALSE
});
Usually file upload will return in array format. So that each uploaded file will have the information like name, type, size, temporary name, error. You can get the file information using print function (print_r($_FILES)). So if you want to display name of the file you have to use something like this $_FILES['filename']['name']
Use print function and debugging tool then save file information using loops.
For more info please check here.
You aren't setting the enctype of the form so the image will never be sent. updated the code to
$form = new Varien_Data_Form(array( 'enctype' => 'multipart/form-data'));

Resources