Laravel - UploadedFile 实例的文件路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25827765/
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 10:05:58  来源:igfitidea点击:

Laravel - file path to UploadedFile instance

phplaravellaravel-4upload

提问by whonoes

I have a Laravel 4.2 API that, when creating a resource, accepts file uploads. The file is retrieved with Input::file('file')

我有一个 Laravel 4.2 API,在创建资源时,它接受文件上传。该文件被检索 Input::file('file')

Now I want to write a script (also in Laravel) that will batch create some resources (so I can't use a HTML form that POSTs to API's endpoint). How can I translate a file path into an instance of UploadedFileso that Input::file('file')will pick it up in the API?

现在我想编写一个脚本(也在 Laravel 中)来批量创建一些资源(所以我不能使用 POST 到 API 端点的 HTML 表单)。如何将文件路径转换为 ​​的实例,UploadedFile以便Input::file('file')在 API 中获取它?

回答by Cody Caughlan

Just construct an instance yourself. The API is:

只需自己构建一个实例。API是:

http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/File/UploadedFile.html

http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/File/UploadedFile.html

So you should be able to do:

所以你应该能够做到:

$file = new UploadedFile(
    '/absolute/path/to/file',
    'original-name.gif',
    'image/gif',
    1234,
    null,
    TRUE
);

Notice:You have to specify the 6th constructing parameter as TRUE, so the UploadedFile class knows that you're uploading the image via unit testing environment.

注意:您必须将第 6 个构造参数指定为 TRUE,以便 UploadedFile 类知道您正在通过单元测试环境上传图像。

回答by Alexandre Thebaldi

  /**
   * 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;
  }