Laravel上传文件在不同的文件夹中

时间:2017-08-21 14:01:50

标签: php laravel

public function upload(Request $request){
    $user = User::findOrFail(auth()->user()->id);

    $filename =  time() . '.jpg';
    $filepath = public_path('uploads/');

    move_uploaded_file($_FILES['filename']['tmp_name'], $filepath.$filename);

    move_uploaded_file($_FILES['filename']['tmp_name'], public_path('uploads/newfolder').$filename);

    echo $filepath.$filename;
}

如何将相同的图像上传到不同的文件夹中 我已经尝试了上面的代码,它在其他文件夹中不起作用。

3 个答案:

答案 0 :(得分:1)

您无法为同一个文件运行move_uploaded_file两次,因为正如其名称所示,它移动文件,因此在第二次运行时,原始文件赢了&#39 ; t已经存在了。

您必须复制文件:

public function upload(Request $request){
    $user = User::findOrFail(auth()->user()->id);

    $filename =  time() . '.jpg';
    $filepath = public_path('uploads/');

    move_uploaded_file($_FILES['filename']['tmp_name'], $filepath.$filename);

    // Note that here, we are copying the destination of your moved file. 
    // If you try with the origin file, it won't work for the same reason.
    copy($filepath.$filename, public_path('uploads/newfolder').$filename);

    echo $filepath.$filename;
}

答案 1 :(得分:0)

你应该试试这个:

尝试将上传文件夹图像复制到新文件夹,如:

use Illuminate\Support\Facades\File;

$imgUpload = File::copy(public_path().'/uploads/'. $filename, public_path().'/newfolder/'. $filename);

希望这对你有用!!!

答案 2 :(得分:0)

use Illuminate\Support\Facades\Storage;    
public function upload(Request $request){
     $filename =  time() . '.jpg';
     $filepath = public_path('uploads/newfolder/');
     $file      = $request->file( "filename" );
     Storage::putFileAs( $filepath, $file, $filename );
     echo Storage::url( 'uploads/newfolder/'.$filename );
}