Laravel 5.1:将上传的文件保留为旧输入 [英] Laravel 5.1: keep uploaded file as old input

查看:67
本文介绍了Laravel 5.1:将上传的文件保留为旧输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 5.1中的表单来发布一些文本并上传文件.看起来像这样(简化版):

I'm using a form in Laravel 5.1 to post some text and to upload a file. It looks like this (simplified version):

{!! Form::open(array('url' => 'foo/bar')) !!}
    {!! Form::text('image_name') !!}
    {!! Form::file('image') !!}
    {!! Form::submit('Submit!') !!}
{!! Form::close() !!}

该文本字段是必需的,因此我在控制器中添加了$validator.如果验证失败,则将用户重定向回表单.我使用withInput()方法重新填充该表单,以便用户不必再次填写该表单:

The textfield is required, so I added a $validator in my controller. If validation fails, the user is redirected back to the form. I use the withInput() method to repopulate the form so that the user doesn't have to fill it in again:

if ($validator->fails()) {
    return redirect()->back()->withInput();
}

这将获得文本字段,下拉列表等的旧输入.但是,如果用户上载了文件,则在验证失败时文件选择将消失,必须再次选择. Laravel中有什么方法可以记住将文件选择作为旧输入吗?

This will get the old input back for textfields, dropdowns etc. But if the user has uploaded a file, the file selection is gone when validation fails and has to be selected again. Is there any way in Laravel to remember file selection as old input?

谢谢!

推荐答案

否,Laravel或任何软件都无法预先填充file输入.您的网站(和任何网站)都不,也不应该知道文件的本地路径.想象一下,如果这样做的话,将会带来安全隐患!您可以诱骗用户上传其SSH私钥或其他内容.

No, the file input can't be prepopulated by Laravel or by any software. Your website (and any website) doesn't and shouldn't know the local path to the file. Imagine the security risks if they did! You could trick a user into uploading their SSH private key or something.

您需要做的就是处理上传的文件,即使有验证错误也是如此.

What you need to do is process the uploaded file regardless, even if there are validation errors.

然后,您可以将其以pending状态存储在数据库中,或者为它分配一些唯一的hash,并在用户会话中存储匹配的hash.关键是要能够识别出属于该特定用户的不完整上传.

Then you could either store it in your database with a pending status, or have some unique hash assigned to it, with a matching hash stored in the user's session. The point is to be able to identify incomplete uploads that belong to this specific user.

然后,当您显示表单时,从会话或数据库中检索那些不完整的文件,并在文件上传旁边显示缩略图.这告诉用户他们不需要重新上传该文件.只要确保他们有办法也将其删除,以防万一他们改变主意.

Then when you display the form, retrieve those incomplete files either from the session or database, and display the thumbnail next to the file upload. This tells the user that they don't need to re-upload that file. Just make sure that they have a way to remove it as well in case they changed their mind.

正确提交表单后,清除会话hash或将数据库状态更新为complete;无论您需要做什么.

Once the form is submitted correctly then clear the session hash or update the database status to complete; whatever you need to do.

这篇关于Laravel 5.1:将上传的文件保留为旧输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆