【问题标题】:How to delete file from public folder in laravel 5.1如何从 laravel 5.1 的公用文件夹中删除文件
【发布时间】:2016-02-23 21:19:16
【问题描述】:

我想从数据库中删除新闻,当我点击删除按钮时,数据库中的所有数据都已删除,但图像仍保留在上传文件夹中。 那么,我该如何工作。 谢谢


这又是我的功能,但不会从公共目录的 images/news 文件夹中删除图像>

 public function destroy($id) {
    $news = News::findOrFail($id);
    $image_path = app_path("images/news/{$news->photo}");

    if (File::exists($image_path)) {
        //File::delete($image_path);
        unlink($image_path);
    }
    $news->delete();
    return redirect('admin/dashboard')->with('message','خبر موفقانه حذف  شد');
}

【问题讨论】:

    标签: laravel


    【解决方案1】:

    使用 php 的 unlink 函数,只需传递文件的确切路径即可取消链接函数:

    unlink($file_path);
    

    如果文件未存储在数据库中,请不要忘记创建文件的完整路径。例如

    $file_path = app_path().'/images/news/'.$news->photo;
    

    【讨论】:

    • 没有从文件夹中删除,只是从数据库中删除
    【解决方案2】:

    您可以按照@Khan 的建议使用 PHP 的 unlink() 方法。

    但如果你想用 Laravel 的方式来做,请改用 File::delete() 方法。

    // 删除单个文件

    File::delete($filename);
    

    //删除多个文件

    File::delete($file1, $file2, $file3);
    

    // 删除文件数组

    $files = array($file1, $file2);
    File::delete($files);
    

    别忘了在顶部添加:

    use Illuminate\Support\Facades\File; 
    

    【讨论】:

    • 不从公用文件夹中删除
    • 通过改变路径解决:$image_path = public_path().'/'.$news->photo;取消链接($image_path);
    • use Illuminate\Support\Facades\File; - 您可以将其添加到您的答案中@moris-io
    • 你也可以尝试删除某个文件夹中的文件,在我的例子中,文件夹名称是'pdf_uploads',所以你可以这样写,$file_path = public_path('pdf_uploads').'/' .$items->文件;
    【解决方案3】:

    首先,你应该去config/filesystems.php并像这样设置'root' => public_path()

    'disks' => [
    
        'local' => [
            'driver' => 'local',
            'root' => public_path(),
    ],
    

    然后,你可以使用Storage::delete($filename);

    【讨论】:

    • 这就是答案。貌似目前 Laravel 的存储系统默认使用 local,这使得删除看起来在 app 文件夹中。错了。
    • 要添加到此答案,您还可以创建一个名为 public_root 的新磁盘并根据需要更新值。
    【解决方案4】:

    这个方法对我有用
    首先,将下面的行放在控制器的开头:

    use File;
    

    在你的 php 文件中的命名空间下面 第二:

     $destinationPath = 'your_path';
     File::delete($destinationPath.'/your_file');
    

    $destinationPath --> public 文件夹内的文件夹。

    【讨论】:

      【解决方案5】:

      尝试使用:

      unlink('.'.Storage::url($news->photo));
      

      查看外观存储调用之前的连接

      【讨论】:

        【解决方案6】:

        试试看:Laravel 5.5

        public function destroy($id){  
              $data = User::FindOrFail($id);  
              if(file_exists('backend_assets/uploads/userPhoto/'.$data->photo) AND !empty($data->photo)){ 
                    unlink('backend_assets/uploads/userPhoto/'.$data->photo);
                 } 
                    try{
        
                        $data->delete();
                        $bug = 0;
                    }
                    catch(\Exception $e){
                        $bug = $e->errorInfo[1];
                    } 
                    if($bug==0){
                        echo "success";
                    }else{
                        echo 'error';
                    }
                }
        

        【讨论】:

          【解决方案7】:

          在不更改 laravel 文件系统配置文件或使用纯 php 取消链接功能的情况下从公共文件夹中删除图像的两种方法:

          1. 使用默认本地存储需要指定公共子文件夹:
          Storage::delete('public/'.$image_path);
          
          1. 直接使用公共存储:
          Storage::disk('public')->delete($image_path);
          

          我建议第二种方法是最好的。

          希望这对其他人有所帮助。

          【讨论】:

            【解决方案8】:

            使用 PHP unlink() 函数,将文件删除

            $path = public_path()."/uploads/".$from_db->image_name;
            unlink($path);
            

            以上将删除$from_db->image_name返回的位于public/uploads文件夹的图像

            【讨论】:

              【解决方案9】:
              public function destroy($id) {
                  $news = News::findOrFail($id);
                  $image_path = app_path("images/news/".$news->photo);
              
                  if(file_exists($image_path)){
                      //File::delete($image_path);
                      File::delete( $image_path);
                  }
                  $news->delete();
                  return redirect('admin/dashboard')->with('message','خبر موفقانه حذف  شد');
              }
              

              【讨论】:

                【解决方案10】:

                删除新闻图片最简单的方法是使用如下的模型事件 如果新闻被删除,模型会删除图像

                首先你应该在模型类use Illuminate\Support\Facades\Storage的顶部导入它 之后在模型类News 你应该这样做

                public static function boot(){
                    parent::boot();
                
                    static::deleting(function ($news) {
                          Storage::disk('public')->delete("{$news->image}");
                    })
                }
                

                或者您可以删除控制器中的图像 这个命令

                Storage::disk('public')->delete("images/news/{$news->file_name}");
                

                但您应该知道默认磁盘是公共的,但是如果您在公共文件夹中创建文件夹并将图像放在上面,您应该在$news->file_name之前设置文件夹名称

                【讨论】:

                • updating 怎么样?模型给出的是最新数据还是旧数据?
                【解决方案11】:

                首先通过构建路径确保文件存在

                if($request->hasFile('image')){
                    $path = storage_path().'/app/public/YOUR_FOLDER/'.$db->image;
                      if(File::exists($path)){
                          unlink($path);
                      }
                

                【讨论】:

                • $path = storage_path().'/app/public/YOUR_FOLDER/'.$db->image; 为我工作
                【解决方案12】:

                如果您将图像存储在 public 文件夹中,请尝试以下步骤:

                例如,您的图片是 sample.jpg,您的路径是 public/img/sample.jpg 所以这段代码会删除你的图片

                use Illuminate\Support\Facades\File;
                .
                .
                .
                
                
                public function deleteImage(){
                
                   $imgWillDelete = public_path() . '/img/sample.jpg';
                   File::delete($imgWillDelete);
                }
                

                【讨论】:

                  【解决方案13】:

                  这是我上传文件并将其保存到数据库和公用文件夹的方法,也是我从数据库和公用文件夹中删除文件的方法。
                  这可以帮助您和学生获得完整的源代码以完成任务。

                  上传文件
                  首先,如果您通过给出路径public_path() 将文件保存到数据库中,一旦它不需要再次在删除方法中使用

                  public function store_file(Request $request)
                  {
                     if($request->hasFile('file'))
                     {
                        $fileExtention = $request->file('file')->getClientOriginalExtension();
                        $name = time().rand(999,9999).$request->filename.'.'.$fileExtention;
                        $filePath = $request->file('file')->move(public_path().'/videos',$name);
                        $video = new Video_Model;
                        $video->file_path = $filePath;
                        $video->filename = $request->filename;
                        $video->save();
                     }
                     return redirect()->back();
                  } 
                  

                  删除文件
                  从您保存时的数据库和公用文件夹中

                  public function delete_file(Request $request)
                  {
                     $file = Video_Model::find($request->id);
                     $file_path = $file->file_path;
                     if(file_exists($file_path))
                     {
                        unlink($file_path);
                        Video_Model::destroy($request->id);
                     }
                     return redirect()->back();
                  }
                  

                  【讨论】:

                    【解决方案14】:

                    对于从公共文件夹中删除文件,我们可以在 Laravel 中使用 File::delete 函数。使用File需要use File进入控制器或者我们可以使用\File。这考虑文件的根目录。

                    // 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);
                    

                    【讨论】:

                      【解决方案15】:

                      仔细按照步骤先获取图片=>

                          $img = DB::table('students')->where('id',$id)->first();
                          $image_path = $img->photo;
                          
                          unlink($image_path);
                          DB::table('students')->where('id',$id)->delete();
                      

                      【讨论】:

                        【解决方案16】:

                        这是一个非常古老的线程,但我看不到解决方案在这里,或者这个线程被标记为已解决。我也遇到了同样的问题,我像这样解决了它

                          $path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
                          if (!File::exists($path)) 
                          {
                            File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
                          }
                        

                        关键是您需要从删除方法中删除“..”。请记住,如果您也使用存储,这也是如此,无论您使用的是文件存储,都不要像 get 那样使用它们

                        use App\Http\Controllers\Controller;
                        use Illuminate\Http\Request;
                        use File; // For File
                        use Storage; // For Storage
                        

                        希望对大家有所帮助。

                        【讨论】:

                          【解决方案17】:

                          更新适用于 Laravel 8.x:

                          以删除图片为例 ->

                          首先在控制器顶部添加文件外观:

                          use Illuminate\Support\Facades\File;
                          

                          然后使用删除功能。如果文件位于“public/”中,则必须使用 public_path() 函数指定路径:

                          File::delete(public_path("images/filename.png"));
                          

                          【讨论】:

                            【解决方案18】:

                            要从文件夹中删除文件,你可以使用 unlink,如果你想从数据库中删除数据,你可以在 laravel 中使用 delete()

                            从文件夹中删除文件

                            取消链接($image_path);

                            用于从数据库中删除记录

                            $flight = Flight::find(1);

                            $flight->delete();

                            【讨论】:

                              【解决方案19】:

                              这适用于 laravel 8

                              use File;
                              
                              if (File::exists(public_path('uploads/csv/img.png'))) {
                                   File::delete(public_path('uploads/csv/img.png'));
                               }
                              

                              【讨论】:

                                【解决方案20】:
                                public function update(Request $request, $id)
                                {
                                    $article = Article::find($id);
                                    if($request->hasFile('image')) {
                                        $oldImage = public_path($article->image);
                                        File::delete($oldImage);
                                        $fileName = time().'.'.$request->image->extension();
                                        $request->image->move(public_path('uploads/'), $fileName);
                                        $image ='uploads/'.$fileName;
                                        $article->update([
                                            'image' => $image,
                                        ]);
                                    }
                                    $article->update([
                                        'title' => $request->title,
                                        'description' => $request->description,
                                    ]);
                                    return redirect()->route('admin.article.index');
                                }
                                

                                【讨论】:

                                  【解决方案21】:

                                  您可以删除文件及其记录:

                                   public function destroy($id)
                                      {
                                  
                                          $items = Reports::find($id); //Reports is my model
                                        
                                  
                                  
                                      $file_path = public_path('pdf_uploads').'/'.$items->file; // if your file is in some folder in public directory.
                                  
                                  
                                    // $file_path = public_path().'/'.$items->file;  use incase you didn't store your files in any folder inside public folder.
                                  
                                          if(File::exists($file_path)){
                                  
                                          File::delete($file_path); //for deleting only file try this
                                          $items->delete(); //for deleting record and file try both
                                  
                                          }
                                  
                                       return redirect()->back()->with('message','client code: '.$items->receipt_no.'  report details has been successfully deleted along with files');
                                  
                                  
                                      }
                                  

                                  noteitems->file 是我在数据库中的属性,我在其中存储了文件的名称,如下所示,

                                  我已将文件存储在目录“public/pdf_uploads/filename”

                                  别忘了在标题中添加这个

                                  use Illuminate\Support\Facades\File; 
                                  

                                  【讨论】:

                                    【解决方案22】:

                                    对于文件语法:

                                    if(File::exists(public_path('upload/test.png'))){
                                                File::delete(public_path('upload/test.png'));
                                            }else{
                                                dd('File does not exists.');
                                            }
                                    

                                    对于存储语法:

                                    if(Storage::exists('upload/test.png')){
                                                Storage::delete('upload/test.png');
                                                /*
                                                    Delete Multiple File like this way
                                                    Storage::delete(['upload/test.png', 'upload/test2.png']);
                                                */
                                            }else{
                                                dd('File does not exists.');
                                            }
                                    

                                    常用方法是: @unlink('/public/admin/pro-services/'.$task->pro_service_image);

                                    【讨论】:

                                      猜你喜欢
                                      • 1970-01-01
                                      • 2014-12-04
                                      • 1970-01-01
                                      • 1970-01-01
                                      • 2014-03-24
                                      • 1970-01-01
                                      • 1970-01-01
                                      • 2018-05-01
                                      • 1970-01-01
                                      相关资源
                                      最近更新 更多