从Laravel 5.2文件夹中删除照片

时间:2016-01-10 03:55:21

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

我需要帮助从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>

这是我存储照片的途径: My Path To Images Folder

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

4 个答案:

答案 0 :(得分: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();
    }

答案 1 :(得分:0)

据我所知,您的路线与表格中的网址不匹配:

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请求

答案 2 :(得分:0)

尝试以下步骤:

首先,从routes.php

中删除此行
Route::delete('photos/{id}', 'FlyersController@destroy');

然后在视图中修改表单标记

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

试一试

答案 3 :(得分:0)

将您的表单方法从post更改为delete。否则,将不会执行'Route :: delete'事件。通常,文件存储在/ storage / app文件夹中。 Laravel为您提供了一些非常容易获取文件的功能