Rretzko's avatar

Problem getting import to work on Vapor via Livewire component

Hi All - I have the following method:

which reports back:

Excel import failed: File [/tmp/exceloKvQyi] does not exist and can therefor not be imported
TempFile name: /tmp/exceloKvQyi
storedFileName: ensembles/memberships/test2383.csv
fileName: test2382.csv
fileSize is good
fileSize: 2157

I'm working on Vapor, so serverless, and thus some additional complexity is layered on. Can anyone help me understand either what I'm doing wrong here or why Vapor isn't finding the file that is demonstrably present? Thanks!

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

Certainly! This is a common issue when working with Laravel Vapor and file uploads, especially with temporary files and the Maatwebsite Excel package.

Problem Explanation

On Laravel Vapor, the filesystem is ephemeral and stateless. This means that, although you can create temporary files, the environment may not persist them as you expect, or the process may run in a different container than the one that created the file. This can cause issues when you try to access a temporary file immediately after creating it.

Your logs show that the file is being created, but the Excel package cannot find it. This is likely due to the stateless nature of Lambda containers on Vapor.

Solution

The best practice on Vapor is to avoid using local temporary files. Instead, you should work directly with files stored on S3. The Maatwebsite Excel package supports importing directly from S3.

How to Import Directly from S3

You can pass the S3 disk and path directly to Excel::import:

Excel::import(
    new EnsembleMembersImport,
    $storedFileName, // This is the S3 path, e.g., 'ensembles/memberships/test2383.csv'
    's3',            // Specify the S3 disk
    \Maatwebsite\Excel\Excel::CSV
);

So, replace this block:

$tempFile = tempnam(sys_get_temp_dir(), 'excel');
file_put_contents($tempFile, \Storage::disk('s3')->get($storedFileName));
Log::info('tempFile name: ' . $tempFile);
Excel::import(new EnsembleMembersImport,
    $tempFile,
    '', //no disk; tmp directory
    \Maatwebsite\Excel\Excel::CSV);
//delete the temporary file
unlink($tempFile);

With this:

Excel::import(
    new EnsembleMembersImport,
    $storedFileName, // S3 path
    's3',            // S3 disk
    \Maatwebsite\Excel\Excel::CSV
);

Full Method (Revised)

Summary

  • Do not use local temp files on Vapor.
  • Import directly from S3 using the disk and path.

This will resolve your issue and is the recommended approach for file processing on Laravel Vapor.

Please or to participate in this conversation.