在Laravel上传文件

时间:2018-10-27 13:27:50

标签: php laravel dropzone

我只是从Laravel开始,然后尝试使用Dropzone JS进行文件上传。我可以成功上传文件,但是它们正在app/Http/Controllers登陆,因此无法公开访问。

似乎正在将此目录视为根目录,因此,如果我将/ uploads指定为文件夹,则它们将进入app/Http/Controllers/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);
}

我还尝试了下面发现的许多其他方法,但是在Chrome的元素检查器中,我发现了500个错误。

来自官方文档

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

从我发现的教程中

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

来自其他教程

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

当前方法看起来不错,但只需要将文件存储在公共/上传文件中即可。

2 个答案:

答案 0 :(得分:2)

改为使用以下路径:

$targetPath = public_path().'/uploads/';

答案 1 :(得分:0)

我还建议为我们的存储路径制定一条完美的路线,以便当有人添加主机名/存储时,它不会向您显示目录,只有文件可以访问

Route::get('storage/{filename}', function ($filename)
{
    $path = storage_path('public/' . $filename);

    if (!File::exists($path)) {
        abort(404);
    }

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});