0

I have Excel Import project using Maatwebsite package in Laravel-5.8. I have been able to perform the Excel import and save it into the database successfully.

UserController

class UserssController extends Controller
{
  public function importExportView()
  {
     return view('import');
  }

  public function import() 
  {
    Excel::import(new UsersImport,request()->file('file'));
    return back();
  }
}

user.blade

<div class="container">
    <div class="card bg-light mt-3">
        <div class="card-header">
            Import Excel
        </div>
        <div class="card-body">
            <form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <input type="file" name="file" class="form-control">
                <br>
                <button class="btn btn-success">Import User Data</button>
            </form>
        </div>
    </div>

However, there is one more thing. I have a sample Excel file. Before import, I want the user to download the sample excel sheet and see how the file format is, and how it should be arranged.

The file is in this directory: public/storage/sample/user.xlsx

How do I modify my code, especially in the view to achieve this?

Thank you.

mikefolu
  • 1,203
  • 6
  • 24
  • 57

2 Answers2

1

There is a download method in the storage class may help you

Storage::download('file.jpg');

you can check more in the docs

Joseph
  • 5,644
  • 3
  • 18
  • 44
1

If you want to download directly in a route function, you can use the response()->download() method directly in the return statement.

There is a small example of file download with this method

/**
 * Download file with "response()->download()" method
 * @param Request $request
 * @param String  $filename containing filename and extension (.xls in this example)
 * @return BinaryFileResponse
 */
public function downloadAction(Request $request, $pathHash, $filename) {
    // Get path from storage directory
    $path = storage_path('app/' . $filename);

    // Download file with custom headers
    return response()->download($path, $filename, [
        'Content-Type' => 'application/vnd.ms-excel',
        'Content-Disposition' => 'inline; filename="' . $filename . '"'
    ]);
}

This method is useful for all files not available in public/storage directory.

You can change the Content-Type header value by the corresponding mime type of the file. There is a table of common file extensions here: https://developer.mozilla.org/fr/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types

MrLizzard
  • 158
  • 9