php 如何将文件从一个位置移动到另一个位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30811480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:04:53  来源:igfitidea点击:

How can I move a file from one location to another?

phplaravellaravel-5

提问by Tiffany Soun

I'm trying to move a file from one place to another place. In this case it is my user profile picture. Since I store my user profile picture base on their username, so when they change their username. I will need to move their profile photo, otherwise, the image link will be broken.

我正在尝试将文件从一个地方移动到另一个地方。在这种情况下,它是我的用户个人资料图片。由于我根据他们的用户名存储我的用户个人资料图片,因此当他们更改用户名时。我需要移动他们的个人资料照片,否则图片链接将被破坏。

I've tried it here:

我在这里试过:

if ( $user->username != Input::get('username')) {
    $new_path = public_path().'/img/logo/'. Input::get('username').'/'.$user->logo_path;
    $old_path = public_path().'/img/logo/'. $user->username.'/'.$user->logo_path;
    $move = File::move($new_path, $old_path);
    $delete = File::delete($old_path);
}


I keep getting:

我不断得到:

enter image description here

在此处输入图片说明

Any suggestions?

有什么建议?

回答by John Shipp

You're moving the file in the wrong direction.

您正在向错误的方向移动文件。

It should be $move = File::move($old_path, $new_path);

它应该是 $move = File::move($old_path, $new_path);

... in other words, the first argument should be the OLD file location, the second argument should be the NEW file location... you have it backwards. :)

...换句话说,第一个参数应该是旧文件位置,第二个参数应该是新文件位置......你把它倒过来了。:)

From the Laravel Docs

来自Laravel 文档

Move A File To A New Location

Storage::move('old/file1.jpg', 'new/file1.jpg');

将文件移动到新位置

Storage::move('old/file1.jpg', 'new/file1.jpg');

Additionally, as said above, you shouldn't have the File::delete either since that file was moved and therefore deleted.

此外,如上所述,您也不应该使用 File::delete,因为该文件已被移动并因此被删除。

So, two things:

所以,两件事:

1) Switch the "old_path" and "new_path" and

1) 切换“old_path”和“new_path”

2) Remove the File::delete line

2) 删除 File::delete 行

回答by user985366

I suggest you store files based on the user ID instead of username, that way you won't have to move anything when the username changes. Only replace the existing file.

我建议您根据用户 ID 而不是用户名存储文件,这样在用户名更改时您就不必移动任何内容。仅替换现有文件。