如何将 Uploadcare 图像保存在表单中?

How to keep Uploadcare image in forms?

我有一个要用 PHP 验证的表格。从 Uploadcare 的小部件上传的海报是该表格的一部分。

有时用户必须返回表单来修复问题 - 错误的电子邮件等。我希望所选的上传文件保留在该表单中。

这在单击后退按钮时有效,但我不能依赖它。我正在使用 PHP POST 变量来重新加载和重新填充表单。

我的问题:我可以使用带有 Uploadcare 输入按钮的 POST 变量来使其 "remember" 并重新加载用户之前上传的所选图片吗?

我当前的代码。

<input type="hidden"
       role="uploadcare-uploader"
       data-preview-step="true"
       data images-only="true"
       name="adposter"
       style="display: inline-block;" />

是否可以这样做:

<input type="hidden"
       role="uploadcare-uploader"
       data-preview-step="true"
       data-images-only="true"
       name="adposter"
       style="display: inline-block;" 
       value="<?php print isset($_POST["adposter"]) ? htmlspecialchars($_POST["adposter"]) : ""; ?>"
/>

与其他领域一样?显然 Uploadcare 输入小部件有自己的处理方式,因此查询。

您可以使用 $_POST 将变量从一种形式传递到另一种形式,就像您描述的使用隐藏字段一样。但这不是很有效,当您将信息写回客户端时,他们可以更改它。

保存这类变量的更好方法是使用$_SESSION:

The session support allows you to store data between requests in the $_SESSION superglobal array. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated. http://php.net/manual/en/intro.session.php

因此,在上传图片后,您将图片 ID 存储在 $_SESSION:

session_start();
$_SESSION['imageid'] = 123456;

然后即使是以后的表格,您也可以再次使用 $_SESSION 变量来访问 imageid:

session_start();
var_dump($_SESSION['imageid']);

int 123456

有关会话的更多信息,请参阅 php 文档:http://php.net/manual/en/book.session.php

已排序。它可以用价值来完成。太棒了!

https://uploadcare.com/documentation/widget/#input-value

作为 documentation says:

The value of [role=uploadcare-uploader] input is either empty or CDN link with file UUID.

If you externally set the value of the input and trigger the DOM change event, it will be reflected in the widget. For example, setting it to a file UUID or a CDN link will show that file as uploaded in the widget. You can do this on a live widget or even before it's actually loaded.

因此您的第二个代码段应该可以正常工作。

您可能还想知道如何设置小部件的值via JS:

var widget = uploadcare.Widget('[role=uploadcare-uploader]');
widget.value("https://ucarecdn.com/e8ebfe20-8c11-4a94-9b40-52ecad7d8d1a/billmurray.jpg");