douhe6181 2018-10-27 13:27
浏览 96
已采纳

Laravel中的文件上传

I'm just starting out with Laravel and trying to get file uploads working using Dropzone JS. I can upload files successfully, but they're landing in app/Http/Controllers, where they're not then publicly accessible.

It seems to be treating this directory as the root, so if I specify /uploads as the folder then they'll go in app/Http/Controllers/uploads (which is obviously no good either). Using ..s doesn't seem to have any effect.

This is my store method for the file uploads:

$ds = DIRECTORY_SEPARATOR;
$storeFolder = '';
if ( ! empty($_FILES)) {
    $tempFile = $_FILES['file']['tmp_name'];
    $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
    $targetFile =  $targetPath. $_FILES['file']['name'];
    move_uploaded_file($tempFile,$targetFile);
}

I've also tried a number of other methods I found (below) but I get 500 errors in Chrome's element inspector with those.

From official docs

$path = $request->file('file')->store('uploads');

From a tutorial I found

$file = $request->file('file');
$destinationPath = '/';
$file->move($destinationPath,$file->getClientOriginalName());

From another tutorial

$uploadedFile = $request->file('file');
$filename = time().$uploadedFile->getClientOriginalName();
Storage::disk('local')->putFileAs(
    '/'.$filename,
    $uploadedFile,
    $filename
);

The current method seems fine but just needs to store files in public/uploads.

  • 写回答

2条回答 默认 最新

  • dongshou9343 2018-10-27 13:45
    关注

    Use this path instead:

    $targetPath = public_path().'/uploads/';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?