来自url的图片是一个字符串而不是UploadFileinstanceOf¿为什么?

时间:2018-04-08 00:05:37

标签: symfony image-uploading ziparchive

我正在寻找这个问题的解决方案很长一段时间。 这是一个img => https://www.siweb.es/images/logo-light.png 我想在OneupUploaderBundle中将此图像存储为zip文件。 因此,当我从文件中获取图像时,使用file_get_contents或CURL,它会正确返回图像,但是当我将此文件传递给$ zip-> addFile();或使用Symfony \ Component \ HttpFoundation \ File \ UploadedFile的uoload服务都返回错误,因为它们接收字符串作为第一个参数。

我想问题是文件不是一个instanceOf UploadeFile但我不知道如何转换它或使用没有表单的Filebag。

public function testAction(Request $request){
    $term = 'https://www.siweb.es/images/logo-light.png';

    $image = $this->getimg($term);

    if ($image instanceof UploadedFile){
        $upload = $this->get('pablo.file_upload_service')->uploadZipFile($image,'test');
    }
    return $this->render('@pabloUser/Test/zip_test.html.twig',['upload' => $image]);
}

private function getimg($url) {
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
    $headers[] = 'Connection: Keep-Alive';
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
    $user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
    $process = curl_init($url);
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($process, CURLOPT_HEADER, 0);
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($process, CURLOPT_TIMEOUT, 30);
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
    $return = curl_exec($process);
    curl_close($process);
    return $return;
}

服务:

public function uploadZipFile(UploadedFile $file,$folder){
    // Check if the file's mime type is in the list of allowed mime types.
    if (!in_array($file->getClientMimeType(), self::$allowedMimeTypes)) {
        $this->pushbulletService->notification('Error en la subida de archivos',sprintf('Files of type %s are not allowed.', $file->getClientMimeType()));
        throw new \InvalidArgumentException(sprintf('Files of type %s are not allowed.', $file->getClientMimeType()));
    }

    // Generate a unique filename based on the date and add file extension of the uploaded file
    $filename = sprintf('%s/%s.%s', $folder, uniqid(), $file->getClientOriginalExtension());

    $zipname = 'file.zip';
    $zip = new \ZipArchive();
    $zip->open($zipname,\ZipArchive::CREATE);
    $zip->addFile($file);
    $zip->close();

    $adapter = $this->filesystem->getAdapter();
    $adapter->write($filename, $zipname);

    return $filename;
}

1 个答案:

答案 0 :(得分:1)

问题是getimg的结果是包含图像数据的(二进制)字符串。要将其作为UploadedFile you have to store the image in a (temporary) file first and then pass the path to it in the constructor传递。

看起来像这样:

$data = $this->getimg(...);

file_put_contents(sys_get_temp_dir() . '/filename.jpg', $data);
$image = new UploadedFile(
    sys_get_temp_dir() . '/logo-light.png',
    'logo-light.png'
);

$upload = $this->get('pablo.file_upload_service')->uploadZipFile($image,'test');