Laravel - file path to UploadedFile instance

送分小仙女□ 提交于 2019-11-30 03:50:14

问题


I have a Laravel 4.2 API that, when creating a resource, accepts file uploads. The file is retrieved with 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 UploadedFile so that Input::file('file') will pick it up in the API?


回答1:


Just construct an instance yourself. The API is:

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.




回答2:


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


来源:https://stackoverflow.com/questions/25827765/laravel-file-path-to-uploadedfile-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!