如何在Laravel 4中删除文件

19

我正在使用laravel 4,需要更改上传的图片,图片位于:

Public
--uploads
---news
----id_news.jpg

在编辑新闻时,我想要更改图片格式,但是我该如何删除并上传其他文件呢?我正在使用:

Input::file('img')->move('uploads/news', $id.'_news.jpg');

问题在于它不能工作,它没有替换文件,那么我该如何删除这张图片以便再次上传。

在 Laravel 3 中,我只使用了:

File::delete('path/to/file');

但我在 Laravel 文档中没有看到有关删除文件的内容。

6个回答

43

我认为你应该将public_path()添加到文件名中,以获取真实的文件路径,就像这样:

File::delete(public_path().$id.'_news.jpg');

13

8
你可以轻松地做到这样:

$filename = public_path().'/uploads/foo.bar';

if (File::exists($filename)) {
    File::delete($filename);
} 

参考资料:Laravel-recipes 删除文件


2
在删除文件之前,您不必检查文件是否存在。但是,由于错误会被静默忽略,因此您可能希望在删除文件后检查它是否不存在。 - Simon Bengtsson
然后你可以在上面的代码中添加一个 else!这意味着检查文件是否存在总是很方便! - Waiyl Karim

2

其他删除用法:

// Delete a single file
File::delete($filename);

// Delete multiple files
File::delete($file1, $file2, $file3);

// Delete an array of files
$files = array($file1, $file2);
File::delete($files);

来源: http://laravel-recipes.com/recipes/133/deleting-a-file

要删除一个文件,您可以使用PHP内置的unlink()函数。使用此函数时,请确保访问文件系统中的文件的权限正确设置。
以下是一个示例,演示如何使用unlink()删除文件:
```php if (!unlink('/path/to/file')) { echo '删除文件失败'; } else { echo '文件删除成功'; } ```

0
$destinationPath = 'uploads/my-image.jpeg'; // from public/

if ( File::exists($destinationPath) ) {
  File::delete($destinationPath);
}

$destinationPath='uploads/'; // 这里是你的文件存储路径 File::exists() // 用于检查文件是否存在,如果存在则删除 - im-sunil

-2

这适用于 Laravel 4.2。

File::delete(storage_path()."/ProductSalesReport-20150316.csv");

// Here are some other paths to directories laravel offers, Hope this
   helps

/* Path to the 'app' folder */
echo app_path();

/* Path to the project's root folder */
echo base_path();

/* Path to the 'public' folder */
echo public_path();

/* Path to the 'app/storage' folder */
echo storage_path();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接