Laravel 5 动态移动图像到另一个文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35009386/
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
Laravel 5 moving image to another folder dynamically
提问by Ikong
I have a fileupload module in my app. I can upload files in img/upload/{container_id}/file_name_here.
我的应用程序中有一个文件上传模块。我可以上传 img/upload/{container_id}/file_name_here 中的文件。
The {container_id} will depend on what folder the user will use.
{container_id} 将取决于用户将使用的文件夹。
The problem I encountered is when they try to edit a record to another folder. The file that they uploaded remains in the old folder.
我遇到的问题是当他们尝试将记录编辑到另一个文件夹时。他们上传的文件保留在旧文件夹中。
I want to move the file also to the new folder the user defines.
我还想将文件移动到用户定义的新文件夹中。
I have here my code, I'm stuck in moving the file.
我有我的代码,我一直在移动文件。
$attachments = Attachment::where('document_id',$id)->select('filename')->get();
$document = Document::findOrFail($id);
foreach($attachments as $attachment)
{
$attachment->filename = base_path().'/public/img/upload/'.$document->container_id."/".$attachment->filename;
}
Document::findOrFail($id)->update($request->all());
$document = Document::findOrFail($id);
$x = Attachment::where('document_id','=',$id)->count();
foreach($attachments as $file)
{
HOW_DO_I_MOVE_THE_FILE????
$x++;
}
return redirect('documents');
回答by schellingerht
Update:
更新:
In your case, you should use rename()
:
在您的情况下,您应该使用rename()
:
rename ('current/path/to/foo', 'new/path/to/foo');
With rename() you can not only rename, but also move! Simply, if the path of the second param differs. So you can use in your loop the attachment path as first param, and a destination path as second.
使用 rename() 您不仅可以重命名,还可以移动!简单地说,如果第二个参数的路径不同。因此,您可以在循环中将附件路径用作第一个参数,将目标路径用作第二个参数。
Documentation: http://php.net/rename
文档:http: //php.net/rename
Below the Laravel approach for moving after upload.
下面是 Laravel 上传后移动的方法。
From the documentation:
从文档:
$request->file('photo')->move($destinationPath);
$request->file('photo')->move($destinationPath, $fileName);
photo
is the name of your file upload input element.
photo
是文件上传输入元素的名称。
Note, you can use the array notation, if you've multi upload, such as:
请注意,如果您有多个上传,则可以使用数组表示法,例如:
foreach ($request->file('photo') as $photo)
{
$photo->move($destinationPath, $chooseYourFileName);
}