如何将来自外部URL的文件保存到Laravel公共目录?

9
我想从外部URL保存一个文件,这个文件可能是任何类型的,比如“jpg、png、mp4”等。我想将它保存在Laravel应用程序的公共目录中。请问我该怎么做?非常感谢您的帮助。
我尝试了以下方法,但它只是将文件保存在我的存储文件夹中:
Storage::put($name, $contents);

谢谢


类Storage将保存在storage文件夹中。使用Laravel常量和函数“public_path()”。 - Giacomo M
抱歉?我该如何使用public_path()保存它? - Siddharth
3个回答

22
在公共路径中创建一个img文件夹,并且:
 $image = file_get_contents("https://logos-download.com/wp-content/uploads/2016/09/Laravel_logo.png");


file_put_contents(public_path('img/a.png'), $image);

完美!像魔法一样运作! - Vinícius

4

请按以下方式使用文件:

   use Illuminate\Support\Facades\File;

并且,接着执行以下操作。
File::put(public_path(   'ANY FILE YOU WANT'    ));

示例:

 File::put( public_path( 'js/a.js'), ' CONTENT ');

嗨,谢谢您的回复。如果我想保存这个文件:https://logos-download.com/wp-content/uploads/2016/09/Laravel_logo.png,该怎么办?我尝试了您的代码,但没有成功。 - Siddharth

0

在身份验证后,从外部URL下载文件。

 public function file_get_contents_curl( $url ) { 

    $ch = curl_init();   
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_URL, $url);  
    $data = curl_exec($ch); 
    curl_close($ch); 

    return $data; 
} 
public function downloadFile( $imgName, $url, $path )
{
    $data = $this->file_get_contents_curl( $url );
    file_put_contents( $path.$imgName, $data ); 
    echo "File downloaded!";

}

根据日期创建新文件夹的代码。

   public function imgBackupFolder( $currentShop ) {

    $folderName = 'export'.DS.str_replace( '.', '_', $currentShop->shopify_domain ).DS.'images'.DS.date( 'Y_m_d' ).DS;
    return $this->createFolder( $folderName );

}
  /*
 * Create folder based on the store,date,export type
 */
private function createFolder( $folderName ) {

    try {
        $path = public_path( $folderName );

        if( !File::isDirectory( $path ) ){
            File::makeDirectory( $path, 0777, true, true );
        }
        return $path;

    } catch (Exception $ex) {
        Log::error( $ex->getMessage() );
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接