我有一个Laravel 4.2 API,在创建资源时接受文件上传。使用检索文件
Input::file('file')
现在我想编写一个脚本(也在Laravel中),它将批量创建一些资源(因此我无法使用POST表单到API终端的HTML表单)。如何将文件路径转换为UploadedFile
的实例,以便Input::file('file')
在API中将其获取?
答案 0 :(得分:12)
自己构建一个实例。 API是:
http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/File/UploadedFile.html
所以你应该能够做到:
$file = new UploadedFile(
'/absolute/path/to/file',
'original-name.gif',
'image/gif',
1234,
null,
TRUE
);
注意:您必须将第6个构造参数指定为TRUE,因此UploadedFile类知道您通过单元测试环境上传图像。
答案 1 :(得分:3)
/**
* Create an UploadedFile object from absolute path
*
* @static
* @param string $path
* @param bool $public default false
* @return object(Symfony\Component\HttpFoundation\File\UploadedFile)
* @author Alexandre Thebaldi
*/
public static function pathToUploadedFile( $path, $public = false )
{
$name = File::name( $path );
$extension = File::extension( $path );
$originalName = $name . '.' . $extension;
$mimeType = File::mimeType( $path );
$size = File::size( $path );
$error = null;
$test = $public;
$object = new UploadedFile( $path, $originalName, $mimeType, $size, $error, $test );
return $object;
}
答案 2 :(得分:0)
这里是 Laravel 8.x 基于 Alexandre Thebaldi 的回答:
use Illuminate\Filesystem\Filesystem;
use Illuminate\Http\UploadedFile;
/**
* Create an UploadedFile object from absolute path
*
* @param string $path
* @param bool $test default true
* @return object(Illuminate\Http\UploadedFile)
*
* Based of Alexandre Thebaldi answer here:
* https://stackoverflow.com/a/32258317/6411540
*/
public function pathToUploadedFile( $path, $test = true ) {
$filesystem = new Filesystem;
$name = $filesystem->name( $path );
$extension = $filesystem->extension( $path );
$originalName = $name . '.' . $extension;
$mimeType = $filesystem->mimeType( $path );
$error = null;
return new UploadedFile( $path, $originalName, $mimeType, $error, $test );
}