在Laravel

时间:2018-04-19 21:40:29

标签: laravel download controller delete-file

我使用fputcsv()生成了一个CSV文件,然后从控制器返回下载的文件。它通过浏览器成功下载,但我也希望在下载后删除该文件。

//controller class
public function downloadCSV{
...
    return response()->download($filePath, $fileName, $headers);
}

我如何调用我的删除功能。

//controller class
csvService->deleteCSV($fileName);

//csvService class
public function deleteCSV($filename) {
    if (File::exists(storage_path($filename))) {
          File::delete(storage_path($filename));
    }
}

我尝试了以下内容。该文件未下载但已成功删除。

public function downloadCSV(...)
    ...
    response()->download($filePath, $fileName, $headers);

    return $csvService->deleteCSV($fileName);
}

1 个答案:

答案 0 :(得分:3)

使用deleteFileAfterSend方法:

return response()->download($filePath, $fileName, $headers)->deleteFileAfterSend(true);

File Download and Responses

//controller class
public function downloadAndDeleteCSV{
    ...
    return response()->download($filePath, $fileName, $headers)->deleteFileAfterSend(true);
}