Laravel Storage put method returns true - php

In my laravel-application I have a <form> where it is possible to upload multiple files. When I submit the form the multiple files get stored into the database, but the table column attachment, which is supposed to store the path of the file, always displays 1 (true).
if (request()->has('attachment_files')) {
$files = request()->attachment_files;
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$filesize = $file->getClientSize();
$path = Storage::disk('local')->put('attachments' . $filename, $extension);
$data = SingleApplicationFile::create([
'files_id' => $application->id,
'single_application_id' => $application->id,
'attachment' => $path,
'attachment_name' => $filename,
'attachment_size' => $filesize,
]);
$attachment_file[] = $data;
new SingleApplicationFile($attachment_file);
}
}
As mentioned, the line $path = Storage::disk('local')->put('attachments' . $filename, $extension); always gives me true and in the database column a "1" is stored.
I used this method before for single file upload, and in that case, the mentioned line stores attachments/somefilename.pdf - so what is the issue here

put() returns a boolean value, which is why you are seeing a 1 in your database column and not the string path to your stored file. You might be thinking of putFile() instead.

Next you need to run
php artisan storage:link
and then you can retrieve the file as
{{ asset('storage/attachments' . $filename) }}
so you may like to save as
if ( Storage::disk('local')->put('attachments' . $filename, $extension) ) {
$path = 'storage/attachments' . $filename;
}

Related

How to save images with different names?

I'm dealing with a few issues regarding multiple images uploads. My project deals with a form the user inputs multiple images that save to a database, but first temporarily stores the images in a directory to show a preview of sorts. In my class, which deals with the uploading of the image I am trying to rename the images as seen below.
I uploaded seven images on the dropdown.
I see that all its images were stored in the database by one.
While it had to be stored under different names.
Controller
public function store(Product $product, Request $request)
{
$path = null;
if ($request->hasFile('file'))
{
$file = $request->file('file');
$name = time();
$extension = $file->getClientOriginalExtension();
$fileName = $name . '.' . $extension;
$path = $file->storeAs($this->path, $fileName, 'public');
}
$gallery = Gallery::create([
'product_id' => $product->id,
'image' => $path,
]);
return response()->json($gallery);
}
$file = $request->file('file');
$name = date('YmdHi');
$extension = $name.$file->getClientOriginalExtension();
In controller , just replace it.

How to upload a image using Slim Framework

I want to storage a image in server and save the path in MySQL, but i'm not finding a good code to do it.
I found this, but does not work:
$container = $app->getContainer();
$container['upload_directory'] = __DIR__ . '../uploads';
$app->post('/photo', function (Request $request, Response $response) use ($app) {
$directory = $this->get('upload_directory');
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['picture'];
if($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$response->write('uploaded ' . $filename . '<br/>');
}
});
function moveUploadedFile($directory, UploadedFile $uploadedFile){
$extension = pathinfo($uploadedFile->getClientFilename(),
PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
Somebody knows how to upload image and save the path in MySQL?
First you need a database connection for MySQL. Read more
Then create a table, e.g. files(id, path, filename)
To insert the record (after the upload) into the table, you could use an SQL statement as follows:
// ...
$filename = moveUploadedFile($directory, $uploadedFile);
$response->getBody()->write('File uploaded: ' . $filename);
$row = [
'path' => $directory,
'filename' => $filename
];
$sql = "INSERT INTO files SET path=:path, filename=:filename;";
$pdo->prepare($sql)->execute($row);
// ...
return $response;
Please note that $response->write('...') will not work. It must be $response->getBody()->write('my content');.
Edit: Make sure that the uploads/ directory exists and the directory has write access. For example chmod -R 1777 uploads/

Save and retrieve file in Laravel

I have difficulty understanding the file save and retrieval in Laravel. I managed to get the file saved into correct path
$fileNameWithExt = $request->file('Agreement_file')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention =$request->file('Agreement_file')->getClientOriginalExtension();
$filenameToStore = $fileName . '_' . $lab_id. '.'.$extention;
$request->Agreement_file->storeAs('agreements', $filenameToStore );
However not I want to create an a-tag to download the file, but cannot manage to get to download the file.
{{$filenameToStore}}
The file download but I get the error "Failed- Server Problem". I do not want to use a same link as these files are confidential and should not be able to be downloaded outside the app.
Something like that?
Step 1:
Create table files id | filename | user_id.
Step 2:
Create model File
Step 3:
Add file row in table.
$fileNameWithExt = $request->file('Agreement_file')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention =$request->file('Agreement_file')->getClientOriginalExtension();
$filenameToStore = $fileName . '_' . $lab_id. '.'.$extention;
$request->Agreement_file->storeAs('agreements', $filenameToStore );
File::create([
'filename' => $filenameToStore,
'user_id' => Auth::id()
]);
Step 4:
Create controller method download.
public function download(){
$filename = $request->input('filename');
$file = File::where('user_id', Auth::id())
->where('filename', $filename)
->firstOrFail();
$path = Storage::path('agreements/' . $filename);
if(Storage::exists($path)){
return Response::download($path, $filename);
}
}
Step 5:
Replace your link:
{{$filenameToStore}}
Or you can build it based on the file ID.

Laravel: The file was not uploaded due to an unknown error

I am trying to upload a file to two different locations. The lcoations being /2x/ adn /3x/. It uploads the file on 3x but doesn't on 2x and throws this error:
The file was not uploaded due to an unknown error
Here is what i am doing:
$photo = $request->file('photo');
if (isset($photo)) {
if ($photo != null || $photo != '') {
$imageSize = getimagesize($photo);
$resolution = $imageSize[0] . 'x' . $imageSize[1];
if ($resolution == '300x300' || $resolution == '450x450') {
if (!file_exists(base_path('uploads/custom_avatar'))) {
mkdir(base_path('uploads/custom_avatar'), 0777, true);
}
$resolution = "3x";
$uploadPath = base_path('uploads/custom_avatar/' . $resolution . '/');
$otherImageResolution = '2x';
$otherImagePath = base_path('uploads/custom_avatar/' . $otherImageResolution . '/');
//echo $otherImagePath;exit;
// saving image
$fileName = $child->id . '_' . time() . '.png';
$photo->move($uploadPath, $fileName);
$photo->move($otherImagePath, $fileName);
// creating records
$childImage = Images::addPhoto($child->id, $fileName, $resolution);
$otherImage = Images::addPhoto($child->id, $fileName, $otherImageResolution);
if ($childImage && $otherImage) {
$result = Child::createChildResponseData($child);
\Log::info('Child avatar added Successfully' . json_encode($childImage));
return response()->json([
'status' => $this->SUCCESS,
'response' => $result,
], $this->SUCCESS);
}
Any help?
Check your code if your file upload code is running two times.
I was facing the same issue & then I find that my file upload code is running two times.
after commenting one of them it's working fine.
You can try this:
$request->file('photo')->move($destination_path, $file_name);
Add DIRECTORY_SEPARATOR between path and filename if needed and
copy that file at new location
copy($destination_path.$file_name, $new_path.$new_file_name);
Check your code if your file upload code is running two times.
You can check this part of the code. Make sure you type it correctly and not repeat it twice.
// Original size upload file
$section_image_file->move($folder, $section_image_name);

Adding an image to a JSON WebService -PHP

Is there any way that I can send images via my JSON Webservice?
Here is my code which looks for new images in a specific folder and return some data including (path, id which is the name of image file and the creation time of the file):
function getAllNewPhotos($lastCHK) {
$dirPath = 'c:\my_images';
$files1 = scandir($dirPath);
$files = array_diff($files1, array('.', '..'));
$newFiles = array();
foreach ($files as $file) {
$createTime = filectime($dirPath . '/' . $file);
$path_data = pathinfo($dirPath . '/' . $file);
if ($createTime > $lastCHK) {
$newFiles[] = array(
'path' => $dirPath . '\\' . $file,
'ID' => $path_data['filename'],
'dateImagAdded' => date('Y-m-d H:i:s', $createTime),
);
}
}
return ($newFiles);
}
Is there any way to send the real image along with the other data which I have already passed?
If you need more clarification, please let me know which part you need more clarification.
Thanks
You can use base64 to encode your image
$imagedata = file_get_contents("/path/to/image.jpg");
// alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

Categories