How to upload multiple files with simple form in symfony 3 - php

I want to create a form with multiple files (images) upload in Symfony 3 and and simple form (i'm not using symfony form builder), but i get only one file (the first file). i'm using POSTMAN for send files via post method.
public function testAction(Request $request)
{
$file = $request->files->get('images');
$ext = $file->guessExtension();
$file_name = time() . '.' . $ext;
$path_of_file = 'uploads/test';
$file->move($path_of_file, $file_name);
var_dump($file);
die();
}

You didn't provide enough information, but maybe the problem is that you didn't set key property as array in Postman like this 'images[]' - than your Symfony endpoint will get an array of UploadedFile objects with all the needed data about your files and you also need to put foreach in your code here:
public function testAction(Request $request)
{
$file = $request->files->get('images');
foreach ($file as $item) {
do some operations
}

Related

How to upload multiple files from single form input in Laravel?

I'm trying to upload multiple pdf files using Laravel. I've made the form using simple HTML and enabled the multiple attribute in the input field. I've tried many other methods mentioned in the stack community but they didn't work for me.
In the controller, I've the following to check whether the files are being uploaded or not. The foreach loop will return the path of the files uploaded.
Controller Code
if ($request->hasFile('corpfile')) {
$file = $request->file('corpfile');
// dd($file);
foreach ($file as $attachment) {
$path = $attachment->store('corporate');
dd($path);
}
HTML Form Code
<input type="file" name='corpfile[]' accept=".xls, .xlsx, .xlsm, .pdf" multiple>
The dd($file) is returning an array with all the files uploaded but the dd($path) is returning only one file's path.
I don't know what the issue is. Any help is appreciated.
you're diying the loop with dd
if you want to store the path in array , you should do that
$path = [];
if ($request->hasFile('corpfile')) {
$file = $request->file('corpfile');
// dd($file);
foreach ($file as $attachment) {
$path[] = $attachment->store('corporate');
}
}

Problem when I try to delete data and files

I'm new in Laravel, and I'm doing a project for my university, and I've two problems when I try to delete:
First error: When I try to delete the records, only the first one (with ID 1) doesn't delete from the table, but the other if deleted from the table and I've already tried some things to fix the error, but I couldn't:
Controller.php:
public function destroy_int($inst_id)
{
$inst = InstitucionEntidadInt::where('id', $inst_id);
$inst->delete();
return redirect('/activities/cons_instituciones_int');
}
Web.php:
Route::delete('/delete_inst_int/{inst_id}', [InstEntController::class, 'destroy_int'])
->name('institucion_int.destroy');
Second error: In some forms, it's necessary to upload and save files in a database (so I save just the name in the database and the files are saved in the public path). And some of this input files are multiple, so I save the names in the database like a JSON (using the json_encode method):
//This is the way that I save the files
$files = [];
if ($request->hasFile('inst_docsoporteNac')) {
foreach ($request->file('inst_docsoporteNac') as $file) {
$name = time() . "_" . $file->getClientOriginalName();
$file->move(public_path('files/institucionesNac'), $name);
$files[] = $name;
}
}
$instentNact->docSoportes = json_encode($files);
So, I'm trying to implement the delete method and I need to delete the files from both places (from the DB and the public path), I don't know how I can do it and I've already tried some "solutions" that I read from some forums (like this).
Controller.php:
public function destroy_nac($inst_id)
{
$inst = InstEntNac::where('id', $inst_id);
$files = InstEntNac::where('id', $inst_id)->get('docSoportes');
foreach (json_decode($files) as $file) {
Storage::delete(public_path('files/institucionesNac/' . $file));
}
$inst->delete();
return redirect('/activities/cons_instituciones_nac');
}
This is the way that I'm using, but I'm getting an error "Object of class stdClass could not be converted to string".
I'll appreciate your solutions for these errors.
For the first error, you can add error handling using this code:
InstitucionEntidadInt::findOrFail($inst_id)->delete();
For the second error, json_decode returns by default stdClass object instead of array. You can tell the function to return array type with second boolean parameter setting it to true:
json_decode($files, true)
https://www.php.net/manual/en/function.json-decode.php

How to track the uploaded size of a file in api laravel 8

I am developing a file system management using laravel 8.
I created a function that accept file.
public function uploadExperiment(Request $request)
{
$file = $request->file('file');
$uniqueId = time();
$fileName = $file->getClientOriginalName();
$filePath = $uniqueId . '/' . $fileName;
Storage::disk('local')->put($filePath, file_get_contents($file));
return response()->json(["success"=>true]);
}
I need to track the uploaded size during the uploading process and this progress I need to save it in a database.
For example, If I want to upload a file with 2GB of size, It will takes time. So any idea about how to track it?
maybe do you want create this:
https://www.itsolutionstuff.com/post/php-laravel-file-upload-with-progress-bar-exampleexample.html
to get size file upload in laravel use:
$size = $request->file('file')->getSize();
maybe could use this for get % of your upload you can use jquery. but if you want to do in php, with this example i think that you have one idea that you could to do:
function timeout_trigger() {
var loaded = file.getLoaded(); // loaded part
p = parseInt(loaded / size);
$(".progress").css("max-width",p+"%");
$(".progress-view").text(p+"%");
if(p!=100) {
setTimeout('timeout_trigger()', 20);
}
}
timeout_trigger();
i think that you have one form and you send it with POST for this use this function.

Trying to get property of non-object when accessing from called function

I'm using yii framework but I think this is related to PHP
In my controller, I have the following code
$model = new Events;
$model->type_id = $type_id;
$checkFileUpload = checkFileUpload($model);
the function checkFileUpload is a custom function which contains
function checkFileUpload($model)
{
$rnd = rand(0, 9999);
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if($uploadedFile->error == 0)
{
$fileName = "{$rnd}-{$uploadedFile}"; // random number file name
$model->image = $fileName;
...
I got the error get property of non-object in $uploadedFile->error.
I've tried to use reference to the model instead, but it is deprecated and does not work for me.
If I use the code of the called function (checkFileUpload) within the controller code, it works fine. I suspect that object is not passed in a correct way.
Any help?
This is because your call to CUploadedFile::getInstance returns null and not the instance you desired.
Null is returned if no file is uploaded for the specified model attribute.
— Yii Documentation
It seems like your file was not correctly uploaded. I am not a Yii Framework user, but the documentation states:
The file should be uploaded using CHtml::activeFileField.
— Yii Documentation
So you should verify that the file was actually correctly uploaded with the proper method from the Yii Framework.
PS: Objects are always passed by reference.
$model = new Events;
$type_id=$model->type_id;
$checkFileUpload = checkFileUpload($model);
function checkFileUpload($model)
{
$rnd = rand(0, 9999);
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if(!isset($uploadedFile->getHasError()))
{
$fileName = "{$rnd}-{$uploadedFile}"; // random number file name
$model->image = $fileName;
The problem occurred because at the time when you are using $uploadedFile->error,the value of $uploadedFile is null.
The following line is not giving you the desired value
$uploadedFile = CUploadedFile::getInstance($model, 'image');
Which means no file has been uploaded.
Try CVarDumper::dump($_FILES,10,true);
This will tell you whether the problem is with the UPLOADING OF THE FILE or GETTING THE DETAILS OF THE UPLOADED FILE
you cant access the private property $_error $uploadedFile->_error if you are trying to. you must call $uploadedFile->getError() in your code. Also $uploadedFile will return null if no file uploaded so you must take care of that as well.
$rnd = rand(0, 9999);
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if(!empty($uploadedFile) && !$uploadedFile->getHasError())
{
$fileName = "{$rnd}-{$uploadedFile}"; // random number file name
$model->image = $fileName;
will work for you.

Repositories with Laravel, saving image to DB

I have setup a repository to create a new resident.
<?php namespace Crescent\Repos;
interface ResidentRepository {
public function create($input);
}
Then in my controller I have, which uses the intervention image class to resize an image and it uploads correctly to the directory, but how can I save the name of the file to the DB using this repo?
public function store()
{
if (Input::hasFile('photo')){
$res = new Residents;
$file = Input::file('photo');
$name = $file->getClientOriginalName();
$input = Input::all();
$image = Image::make(Input::file('photo')->getRealPath())->resize(200, 200);
$image->save(public_path() . '/uploads/residents/' . $input['photo']->getClientOriginalName());
$res->photo = $name; // This doesn't work
}
$this->resident->create(Input::all());
}
Everything else works all the data, but the image isn't storing the name just showing some temp dir/name like /tmp/phpIX7KcY
I see that you have done $res = new Residents; and $res->photo = $name; but you haven't done $res->save(); which would have saved the name to the table corresponding to Residents. Also since you haven't added anything else to $res, only the photo would be saved.
Replace the code in your controller with the following:
public function store()
{
$input = Input::all();
if (Input::hasFile('photo')){
$file = Input::file('photo');
$name = $file->getClientOriginalName();
$image = Image::make(Input::file('photo')->getRealPath())->resize(200, 200);
$image->save(public_path() . '/uploads/residents/' . $input['photo']->getClientOriginalName());
$input['photo'] = $name;
}
$this->resident->create($input);
}
If in your code $this->resident->create(Input::all()); saves all data properly except the photo, it is because by passing Input::all() you're saving everything exactly as it was received from the client and the filename received from the resizing operation isn't present in Input::all(). By assigning Input::all() to the variable $input and doing $input['photo'] = $name;, the location of the file on the server is stored instead of the location on the client. So, by doing $this->resident->create($input);, the location on the server is stored along with other data received from the client.

Categories