anonymouse703's avatar

How to download the from external link and save the downloaded image into storage ?

I have problem in downloading the image and rename it to save in the storage link. The scenario now is our client want to upload the data from excel file which contains outside url link of the image and he want to download the image into the local folder (which I want to save at the storage) and rename the image into random string.

This is my current code but not working just a structure.

 if (!empty($row[12])) {

 //download the file
 //ex $row[12] = https://fastly.picsum.photos/id/13/200/300.jpg?hmac=UHtWCvsKxIfcA_gIse7Rc6MH6nI3OGl0dzaCSSsYqas

 $contents = file_get_contents($row[12]);

 // cache the file
 $file = $row[12];

 // generate a new filename. getClientOriginalExtension() for the file extension
 $filename = 'profile-photo-' . time() . '.' . $file->getClientOriginalExtension();

 // save to storage/app/stocks as the new $filename
 $path = $file->storeAs('stocks', $filename);


 }
0 likes
7 replies
LaryAI's avatar
Level 58

You can use the Storage facade to save the file to the storage directory. You can also use the file_get_contents() function to get the contents of the file from the external URL.

if (!empty($row[12])) {
    // Get the contents of the file from the external URL
    $contents = file_get_contents($row[12]);

    // Generate a new filename
    $filename = 'profile-photo-' . time() . '.jpg';

    // Save the file to the storage directory
    Storage::put('stocks/' . $filename, $contents);
}

This should save the file to the storage/app/stocks directory with the new filename.

1 like
anonymouse703's avatar

@LaryAI What if there's another extension like png from that external url? the problem is the images from the external link has png and other format.

Snapey's avatar

unless your excel file contains only one image, using time will not be sufficient to create a unique filename

you should create a long random string

second problem is that your $file is not an uploaded file object so you cannot call functions on it. if you want the extension, use string functions to split off the final extension

Personally, I would load the image with the Intervention image extension and then manipulate it there ensuring consistent sizing and file type

anonymouse703's avatar

@Snapey I saw this one but some functions are deprecated because it's from 5.6 version

$image = $outside_url

$tempImage = tempnam(sys_get_temp_dir(), 'profile-img'.rand(0,100));

copy($image, $tempImage);

response()->download($tempImage);

$downloadedImage = new File($tempImage);
$imageName = md5(time()).'.'.$downloadedImage->extension();

// Upload
Storage::putFileAs('avatars', $downloadedImage, $imageName);

return $imageName;
1 like
uniksk's avatar

This is how I am doing it using helper function

function copy_file($source_path, $dest_path, $fileextension = "png")
    {
        // Hash the file url to make it unique
        $filename = md5($source_path . '_' . time());

        // Prepare the path where the file has to be uploaded
        $pathToCopy = $_SERVER['DOCUMENT_ROOT'] . '/storage/' . $dest_path . $filename . '.' . $fileextension;

        // Copy the file to the destination
        copy($source_path, $pathToCopy);

        // Prepare the file path to store in database
        $pathToStore = 'storage' . '/' . $dest_path . $filename . '.' . $fileextension;

        return $pathToStore;
    }

Here,

$source_path is the public url

$dest_path is your local folder path inside storage>public folder

$fileextension is a optional parameter to define the extension of file, by default is .png.

anonymouse703's avatar

@all I solved it though it's a many code

 if (!empty($row[12])) {
                $download_image = $row[12];
                $original_name = basename($download_image); 
                $original_extension = substr($original_name, strrpos($original_name, '.')); // ".jpg"
                $types = array(
                    'image/avif' => '.avif',
                    'image/avif' => '.avifs',
                    'image/bmp' => '.bmp',
                    'image/cgm' => '.cgm',
                    'image/g3fax' => '.g3',
                    'image/heic' => '.heif',
                    'image/heic' => '.heic',
                    'image/ief' => '.ief',
                    'image/jpeg' => '.jpe',
                    'image/jpeg' => '.jpeg',
                    'image/jpeg' => '.jpg',
                    'image/jpeg' => '.pjpg',
                    'image/jpeg' => '.jfif',
                    'image/jpeg' => '.jfif-tbnl',
                    'image/jpeg' => '.jif',
                    'image/pjpeg' => '.jpe',
                    'image/pjpeg' => '.jpeg',
                    'image/pjpeg' => '.jpg',
                    'image/pjpeg' => '.pjpg',
                    'image/pjpeg' => '.jfi',
                    'image/pjpeg' => '.jfif',
                    'image/pjpeg' => '.jfif-tbnl',
                    'image/pjpeg' => '.jif', //end
                    'image/png' => '.png',
                    'image/prs.btif' => '.btif',
                    'image/svg+xml' => '.svg',
                    'image/svg+xml' => '.svgz',
                    'image/tiff' => '.tif',
                    'image/tiff' => '.tiff',
                    'image/vnd.adobe.photoshop' => '.psd',
                    'image/vnd.djvu' => '.djv',
                    'image/vnd.djvu' => '.djvu',
                    'image/vnd.dwg' => '.dwg',
                    'image/vnd.dxf' => '.dxf',
                    'image/vnd.fastbidsheet' => '.fbs',
                    'image/vnd.fpx' => '.fpx',
                    'image/vnd.fst' => '.fst',
                    'image/vnd.fujixerox.edmics-mmr' => '.mmr',
                    'image/vnd.fujixerox.edmics-rlc' => '.rlc',
                    'image/vnd.ms-modi' => '.mdi',
                    'image/vnd.net-fpx' => '.npx',
                    'image/vnd.wap.wbmp' => '.wbmp',
                    'iimage/vnd.xiff' => '.xif',
                    'image/webp' => '.webp',
                    'image/x-adobe-dng' => '.dng',
                    'image/x-canon-cr2' => '.cr2',
                    'image/x-canon-crw' => '.crw',
                    'image/x-cmu-raster' => '.ras',
                    'image/x-cmx' => '.cmx',
                    'image/x-epson-erf' => '.erf',
                    'image/x-freehand' => '.fh',
                    'image/x-freehand' => '.fh4',
                    'image/x-freehand' => '.fh5',
                    'image/x-freehand' => '.fh7',
                    'image/x-freehand' => '.fhc',
                    'image/x-fuji-raf' => '.raf',
                    'image/x-icon' => '.ico',
                    'image/x-kodak-dcr' => '.dcr',
                    'image/x-kodak-k25' => '.k25',
                    'image/x-kodak-kdc' => '.kdc',
                    'imimage/x-minolta-mrw' => '.mrw',
                    'image/x-nikon-nef' => '.nef',
                    'image/x-olympus-orf' => '.orf',
                    'image/x-panasonic-raw' => '.raw',
                    'image/x-panasonic-raw' => '.rw2',
                    'image/x-panasonic-raw' => '.rwl',
                    'iimage/x-pcx' => '.pcx',
                    'image/x-pentax-pef' => '.pef',
                    'image/x-pentax-pef' => '.ptx',
                    'image/x-pict' => '.pct',
                    'image/x-pict' => '.pic',
                    'image/x-portable-anymap' => '.pnm',
                    'image/x-portable-bitmap' => '.pbm',
                    'image/x-portable-graymap' => '.pgm',
                    'image/x-portable-pixmap' => '.ppm',
                    'image/x-rgb' => '.rgb',
                    'mage/x-sigma-x3f' => '.x3f',
                    'image/x-sony-arw' => '.arw',
                    'image/x-sony-sr2' => '.sr2',
                    'image/x-sony-srf' => '.srf',
                    'image/x-xbitmap' => '.xbm',
                    'image/x-xpixmap' => '.xpm',
                    'image/x-xwindowdump' => '.xwd',
                    
                );
                $img = file_get_contents($download_image);
                $stored_name = 'stock-image-' . time(). $original_extension;
                if ($img) {
                    file_put_contents($stored_name, $img);
                    $finfo = finfo_open(FILEINFO_MIME_TYPE);
                    $mimetype = finfo_file($finfo, $stored_name);

                    if (isset($types[$mimetype])) {
                        if ($types[$mimetype] != $original_extension) {
                            rename($stored_name, 'stock-image-' . $types[$mimetype]);
                        }
                    }
                    finfo_close($finfo);
                    
                }
                Storage::put('public/stocks/' . $stored_name, $img);
                $row[12] = $stored_name;
            }

Please or to participate in this conversation.