Home > other >  I converted an array into csv, then I get an error when I try to upload it to s3
I converted an array into csv, then I get an error when I try to upload it to s3

Time:09-23

Basically what I want to do is convert my array to csv file, then upload it to amazon s3... Below is the code on making the csv file and uploading it to s3...

$output = [...] // This is my array

$file = fopen("C:\Users\User\Desktop\myFile.csv", "w");

foreach ($output as $row) {
    fputcsv($file, $row);
}

fclose($file);

$path = Storage::disk('s3')->put("/hello.csv", $file, [
    'visibility' => 'public',
    'mimetype' => 'text/csv'
]);

The thing is, if I try to open the created csv file in desktop, it works perfectly.

The error that I get is:

mb_strlen() expects parameter 1 to be string, resource given

The "visibility" and "mimetype" in the put method is what I found on the net, but even without it, it still shows the same error...

Also, according to the laravel docs, the put method supports PHP resource:

The put method may be used to store file contents on a disk. You may also pass a PHP resource to the put method, which will use Flysystem's underlying stream support.

CodePudding user response:

I got it now with the help of my senior... basically you need to put the filename with file directory in the put() method, same if you use putFileAs()

$output = [...] // This is my array

$filename = "C:\Users\User\Desktop\myFile.csv";
$file = fopen($filename, "w");

foreach ($output as $row) {
    fputcsv($file, $row);
}

fclose($file);

$path = Storage::disk('s3')->put("/hello.csv", $filename, [
    'visibility' => 'public',
    'mimetype' => 'text/csv'
]);

CodePudding user response:

Are you storing the CSV locally (temporarily) before you upload to S3? If so maybe its a path issue?

If it is not a path issue I would try the upload with an existing CSV file. See if this works then you can eliminate the upload part of the code as an issue.

  • Related