【问题标题】:Delete Photo from folder Laravel 5.2从文件夹 Laravel 5.2 中删除照片
【发布时间】:2016-04-14 14:27:37
【问题描述】:

我需要帮助从 Laravel 5.2 的文件夹中删除照片。 当我删除照片时,它会从数据库中删除,但不会从文件夹中删除。

这是我的路线

Route::group(['middleware' => ['web']], function () {
    Route::resource('flyer', 'FlyersController');

   Route::delete('photos/{id}', [
    'uses' => '\App\Http\Controllers\FlyersController@destroyPhoto',
    'as'   => 'flyer.destroy'
]);

});

这是我的 Photo.php 模型: (删除照片在底部)

<?php

namespace App;

use Image;
use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpFoundation\File\UploadedFile;


class Photo extends Model {

    /**
     * @var string
     * The associated table.
     */
    protected $table = "flyer_photos";

    /**
     * @var array
     * Fillable fields for a photo.
     */
    protected $fillable = ['name', 'path', 'thumbnail_path'];

    /**
     * @var
     * The UploadedFile instance.
     */
    protected $file;

    /**
     * @var
     * The file name instance.
     */
    protected $name;


    /**
     * A photo belongs to a flyer
     */
    public function flyer() {
        return $this->belongsTo('App\Flyer');
    }


    /**
     * Make a new instance from an uploaded file.
     */
    public static function fromFile(UploadedFile $file) {
        // Make a new instance.
        $photo = new static;

        // Assign the Uploaded file to the $file object.
        $photo->file = $file;

        // Set $photo to the fill properties, which are
        // the name, path, and thumbnail path of a photo.
        $photo->fill([
            'name' =>  $photo->setFileName(),
            'path' =>  $photo->filePath(),
            'thumbnail_path' =>  $photo->thumbnailPath()
        ]);

        // Then return the photo.
        return $photo;
    }


    /**
     * Get the photos base directory.
     */
    public function baseDir() {
        return 'FlyerPhotos/photos';
    }


    /**
     * This function gets the name and extension of a photo.
     */
    public function setFileName() {

        // Set $t = to time()
        $t = time();
        // This will reduce the likelihood of a double call because it will
        // only be a problem if the calls spanned a minute (vs a second),
        $t -= $t % 60;

        // hash the name of the file with the $t function.
        $hash  = sha1(
            $t . $this->file->getClientOriginalName()
        );

        // Get the extension of the photo.
        $extension = $this->file->getClientOriginalExtension();

        // Then set name = merge those together.
        return $this->name = "{$hash}.{$extension}";
    }


    /**
     * Get the full file path of the photo, with the name.
     */
    public function filePath() {
        return $this->baseDir() . '/' . $this->name;
        // Ex: 'FlyerPhotos/photos/foo.jpg'
    }


    /**
     * Get the full file thumbnail path of the photo, with the name.
     */
    public function thumbnailPath() {
        return $this->baseDir() . '/tn-' . $this->name;
        // Ex: 'FlyerPhotos/photos/tn-foo.jpg'
    }


    /**
     * Upload the file to the proper directory.
     */
    public function upload() {

        // Move the file instance to the base directory with the file name.
        $this->file->move($this->baseDir(), $this->name);

        // Make the thumbnail.
        $this->makeThumbnail();

        return $this;
    }


    /**
     * Function to make the actual thumbnail.
     * -- make and save reference the Image intervention library, not Eloquent. --
     */
    protected function makeThumbnail() {
        Image::make($this->filePath())->fit(200)->save($this->thumbnailPath());
    }



/**
 * Delete the photo path and thumbnail path in DB.
 * Access the delete function in FlyerController@destroyPhoto method
 */
public function delete() {

    \File::delete([
        $this->filePath(),
        $this->thumbnailPath()
    ]);

    parent::delete();
}


}

这是我的控制器:(缩短)

<?php

namespace App\Http\Controllers;

use Auth;
use App\User;
use App\Flyer;
use App\Photo;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Requests\FlyerRequest;
use App\Http\Controllers\Controller;
use App\Http\Requests\AddPhotoRequest;
use App\Http\Requests\UserEditRequest;


class FlyersController extends Controller {

    /**
     * Add photos to flyer.
     */
    public function addPhoto($zip, $street, AddPhotoRequest $request) {

        // Set $photo to the fromFile() function,
        // and get the $requested file which is set to 'photo',
        // and upload it using the upload function().
        // -- 'photo' comes from the <script> tags in show.blade.php.

        // Create a new photo instance from a file upload.
        $photo = Photo::fromFile($request->file('photo'))->upload();

        // Set Flyer::loacatedAt() in (Flyer Model)
        // = to the zip and street, and add the photo.
        // -- Find the flyer and add the photo.
        Flyer::locatedAt($zip, $street)->addPhoto($photo);

    }


    /**
 * Delete a photo.
 * -- Access delete() in Photo.php Model --
 */
public function destroyPhoto($id) {

    Photo::findOrFail($id)->delete();

    return redirect()->back();

}


}

这是我的观点:

<div class="img-wrap">
<form method="post" action="{{ route('flyer.destroy', ['id' => $photo->id]) }}" enctype="multipart/form-data">
{!! csrf_field() !!}
<input type="hidden" name="_method" value="DELETE">
@if ($user && $user->owns($flyer))
<button type="submit" class="close">&times;</button>
 @endif
<a href="/project-flyer/{{ $photo->path }}" data-lity>
<img src="/project-flyer/{{ $photo->thumbnail_path }}" alt="" data-id="{{ $photo->id }}">
</a>
</form>
</div>

这是我存储照片的路径:

(图片和缩略图存储在同一个文件夹中,以tn-开头的照片是缩略图)

【问题讨论】:

    标签: javascript php laravel image-processing laravel-5.2


    【解决方案1】:

    我让它工作了,我只需要在 Photo.php 中的删除函数中更改一些内容以更正我正在使用的路径。

    /**
         * Delete the photo path and thumbnail path in DB.
         * Access the delete function in FlyerController@destroyPhoto method
         */
        public function delete() {
    
            $image = $this->path;
            $thumbnail_image = $this->thumbnail_path;
    
            File::delete([
                $image,
                $thumbnail_image
            ]);
    
            parent::delete();
        }
    

    【讨论】:

      【解决方案2】:

      据我所知,您的路由与表单中的 URL 不匹配:

      Route::delete('photos/{id}', 'FlyersController@destroy');
      

      形式是:

      <form method="post" action="/project-flyer/FlyerPhotos/photos/{{ $photo->id }}">
      

      假设你的路由组没有嵌入到另一个路由中,你形成的动作路径应该是:

      /photos/{{ $photo->id }}
      

      另外,如果您没有真正的 DELETE AJAX 请求并且所有删除​​都来自浏览器,为什么不让它成为真正的 POST 路由而不是方法欺骗呢?例如。

      Route::post('photos/delete/{id}', 'FlyersController@destroy');
      

      您的 destroy() 方法具有重定向功能,因此无论如何您都无法将其用于 RESTful AJAX 请求

      【讨论】:

      • 我尝试了两种方法,它只是给我找不到 url
      • Photo.php 中的 delete() 函数可能有问题?
      • 不,未找到意味着您的路由错误——您点击了错误的 URL(不是来自 routes.php 的那个)。如果您的应用程序到达控制器,您会看到不同的错误。检查 Chrome 中的“网络”选项卡,并在单击“删除”时查看您的网站的确切位置。然后将其与“php artisan route:list”条目进行比较——你会发现错误在哪里!
      • 我检查了从 /project-flyer/FlyerPhotos/photos/{{ $photo->id }} 到 {{/photos/{{ $photo->id }},然后我检查了删除按钮将我带到哪里。它会带我去执行表单中的任何操作。
      • 您的 php artisan route:list 是否包含此删除路线?可以在这里展示一下吗?
      【解决方案3】:

      试试这些步骤:

      首先,从routes.php中删除这一行

      Route::delete('photos/{id}', 'FlyersController@destroy');
      

      然后在你的视图中修改表单标签

      <form method="post" action="{{ route('flyers.destroy', ['id' => $flyer->id]) }}">
      

      试试看

      【讨论】:

      • 是的,我让它工作了!虽然我所做的是这个
        这对于路线 Route::delete('photos/{id}', [ 'uses' => '\App\Http\Controllers\FlyersController@destroy', 'as' => 'flyer.destroy' ]); 和 this 用于 delete() 方法 public function delete() { \File::delete([ $this->filePath(), $this->thumbnailPath() ]);父::删除(); }
      • 现在一切正常,但是,文件中的照片仍然存在。它不是一件太大的事情,但如果他们也可以删除那将是很好的。有没有办法做到这一点?
      【解决方案4】:

      将表单方法从发布更改为删除。否则 'Route::delete' 事件将不会被执行。通常文件存储在 /storage/app 文件夹中。 Laravel 提供了一些函数让你轻松获取文件

      【讨论】:

      • 现在即使使用表单中的方法 POST 也可以正常工作,但正如我在下面所述,文件夹中的文件没有被删除。
      猜你喜欢
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多