首页 > 解决方案 > 从 url 上传文件

问题描述

大家好 :) 我如何从 url 上传文件?(我读了很多关于这个的问题,但没有任何工作......)这是我的代码:

$url = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';

$file = file_get_contents($url);
if ($file != NULL) {
    $fileName = md5(uniqid()) . '.' . $file->guessExtension();

    $file->move(
        $this->getParameter('image_directory'), $fileName
    );
}

在这里,我只想从 url 下载图像并将其移动到一个目录(之后我会将路径保存在数据库中),但是使用此代码我有这个错误:

调用字符串上的成员函数guessExtension()

标签: phpfilesymfonyupload

解决方案


file_get_contents是读取文件的内容(txt、xml 等)。
相反,您应该使用 linux command wget。您可以使用 PHP 函数运行它exec

$url = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';

//Execute wget
$file=exec("wget http://www.example.com/file.xml");
if ($file != NULL) {
    $fileName=md5(uniqid()).'.'.$file->guessExtension();
    $file->move($this->getParameter('image_directory'), $fileName);
}

推荐阅读