Home > Back-end >  How to read file Laravel?
How to read file Laravel?

Time:06-06

I load file using this:

public function fileUpload(Request $req)
{
    $req->validate([
        'file' => 'required|mimes:csv,txt,xlx,xls,pdf|max:2048'
    ]);
    $fileModel = new File();
    if ($req->file()) {
        $fileName = time() . '_' . $req->file->getClientOriginalName();
        $filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
        $fileModel->name = time() . '_' . $req->file->getClientOriginalName();
        $fileModel->file_path = '/storage/' . $filePath;
        $fileModel->save();

        $this->read($fileModel->file_path);

        return back()
            ->with('success', 'File has been uploaded.')
            ->with('file', $fileName);
    }
}

Then I tried to read file after upload file:

public function read($path)
{
   $file = FileStorage::get($path);
   dd($file);
}

But I get this error:

File does not exist at path /storage/uploads/1654468183_test.csv.

How to specify path properly?

CodePudding user response:

I would do this way:

if ($req->file()) {
        $fileName = time() . '_' . $req->file->getClientOriginalName();
        $filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
        $fileModel->name = $fileName; //<--set the right filename
        $fileModel->file_path = '/storage/' . $filePath;
        $fileModel->save();

        $this->read($fileModel->file_path);

        return back()
            ->with('success', 'File has been uploaded.')
            ->with('file', $fileName);
    }

CodePudding user response:

change this line

$filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');

to this

$filePath = $req->file('file')->storeAs('uploads/', $fileName, 'public');

  • Related