我正在尝试创建一个类,将数组转换为纯文本和文件。但是,当我试图将其保存为tmpfile并共享它时,纯文本工作正常,但我会收到错误。
我的控制器看起来像:
public method index() {
$props = ['foo'=>'bar']; //array of props;
return response()->download(MyClass::create($props);
// I've also tried using return response()->file(MyClass::create($props);
}我的类看起来像:
class MyClass
{
// transform array to plain text and save
public static function create($props)
{
// I've tried various read/write permissions here with no change.
$file = fopen(tempnam(sys_get_temp_dir(), 'prefix'), 'w');
fwrite($file, implode(PHP_EOL, $props));
return $file;
}
// I've also tried File::put('filename', implode(PHP_EOL, $props)) with the same results.
}我得到了一个没有发现异常的文件:
The file "Resource id #11" does not exist.
我尝试过tmpfile、tempname和其他文件,并得到了相同的异常。我尝试过传递MyClass::create($props)'uri‘,我得到了
The file "" does not exist
这是因为我的副手犯了错误,还是我做错了?
发布于 2019-02-09 18:27:11
您的代码混淆了文件名和文件句柄的用法。
在create定义中,$file是fopen()的结果,“资源”值也是fopen()的结果,也就是打开的文件句柄。由于您是return $file,所以MyClass::create($props)的结果也是文件句柄。
Laravel 方法需要一个字符串,即文件名来访问;当给定一个资源时,它会悄悄地将其转换为string,从而导致所看到的错误。
要获得文件名,需要对create函数进行两次更改:
tempnam(sys_get_temp_dir(), 'prefix')的结果放在变量中,例如$filename,然后调用$file = fopen($filename, 'w');$filename而不是$file还应该在返回之前添加对fclose($file)的调用,以便在将数据写入文件后干净地关闭该文件。
https://stackoverflow.com/questions/54603589
复制相似问题