如何从外部 url Laravel 公共目录保存文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46401872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:43:01  来源:igfitidea点击:

How can I save file from external url Laravel public directory

phplaravelfile

提问by Siddharth

I wanted to save a file from External Url which would have any kind of file like say "jpg, png, mp4 etc"

我想从 External Url 保存一个文件,该文件可以包含任何类型的文件,例如“jpg、png、mp4 等”

I want to save it in the public directory of Laravel App. How could I do that? Any help will be highly appreciated.

我想把它保存在 Laravel App 的公共目录中。我怎么能那样做?任何帮助将不胜感激。

I tried the following thing, but it's saving file in my storage folder:

我尝试了以下操作,但它将文件保存在我的存储文件夹中:

Storage::put($name, $contents);

Thanks

谢谢

回答by sa-fm

create an img folder in public path and :

在公共路径中创建一个 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);

回答by sa-fm

use File like below

使用如下文件

   use Illuminate\Support\Facades\File;

and then

进而

File::put(public_path(   'ANY FILE YOU WANT'    ));

example:

例子:

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

回答by Liz Eipe C

Download files from external URL after authentication.

认证后从外部 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!";

}

Code for creating a new folder based on the date.

基于日期创建新文件夹的代码。

   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() );
    }

}