Laravel File Upload and File_hash as name Laravel File Upload and File_hash as name laravel laravel

Laravel File Upload and File_hash as name


Note: as of Laravel 5.4 the hashName() function no longer generates the file name based on the content hash of the file. To accomplish this you will need to use md5_file() manually.


The hashing answer

Laravel has a method on the file uploader called hashName() that according to the API docs generates "a filename for the file that is the MD5 hash of the contents". I used this recently in a project to do exactly what you are trying to do using that and md5_file(). Here is an example of how I accomplished it:

View

<form method="POST" action="/controller" files="true" enctype="multipart/form-data">    {!! csrf_field() !!}    <input type="file" id="file-list" name="file-list[]" multiple="true" />    <button type="submit">Upload Files</button></form>

Controller

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Http\Requests;use App\Image;use App\Filename;use Storage;class ImageController extends Controller{    /**     * Store an uploaded file.     *     * @param  \Illuminate\Http\Request  $request     * @return \Illuminate\Http\Response     */    public function store(Request $request)    {        $disk = Storage::disk('images');        foreach ($request->file('file-list') as $file) {            $filename = Filename::first();            $disk->putFile('', $file);            Image::create([                'filename' => $filename->name,                'title' => $file->getClientOriginalName(),                'extension' => $file->guessClientExtension(),                'size' => $file->getClientSize(),                'mime' => $file->getClientMimeType(),                'hash' => md5_file($file->getRealPath()),            ]);            $filename->delete();        }    }}

The Excel problem

Excel does this to me too sometimes. This question might be related. I'm not sure there is much you can do here unless you have control over the uploads in which case you could just avoid opening them before you hash check.