0

I've a form that insert some values using AJAX, and now I want to add also an image, but I can't get the image simply using the superglobal $_FILE['file_name'] in the PHP code, cause the comunication with PHP is under AJAX. So I'm wondering if I could load the file from the PHP using the file's path, infact I could simply pass it throught the JS/AJAX.

Or it's a method that permit me to take the whole file binary code from the JS/AJAX, then pass it to the PHP and finallu put it in a BLOB of the SQL db?

Ps.: obviously I must use the ajax

4

3 回答 3

0

我对通过 AJAX 上传文件没有任何专业知识。但是,如果您需要帮助将文件作为 BLOB 插入数据库,我可以提供一些帮助。

使用PDO相当容易。他们有一个专门介绍有关LOB的详细信息的页面。

$stmt = $db->prepare("INSERT INTO table (image) values (?)");

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt->bindParam(1, $fp, PDO::PARAM_LOB);

$stmt->execute();
于 2012-10-12T20:26:07.457 回答
0

如果服务器上已经存在该文件,我认为最好通过 AJAX 将文件路径传递给 PHP,然后使用 PHP 的file_get_contents函数将其读入。

如果服务器上不存在该文件,您最好提交一个表单。在服务器上执行的 PHP 无法获取文件路径并从客户端获取文件。

如果您可以使用 jQuery,您可以使用 HTML 表单并捕获提交事件,将表单序列化为变量,通过 AJAX 传递,并返回 false 以防止表单提交(导致页面重新加载)。


编辑

再三考虑,serialize这不是解决方案的唯一部分。那只会让您获得文件输入的值,而不是文件的内容。获取内容会更加乏味。不过,看起来 W3C 正在做一些事情

最好只使用标准的 HTML 表单。

于 2012-10-12T20:03:18.953 回答
0

目前 AJAX 不允许您上传文件。

您只需要使用常规方法即可。

但是,Firefox 和 Chrome 有点可能。但这种方法在 IE 中不起作用,而且相当复杂。

编辑

可以考虑让 Javascript 使用此https://developer.mozilla.org/en-US/docs/DOM/FileReader,将其序列化并使用 AJAX 通过 POST 发布。有点绕。FileReader 适用于 Chrome 和最新版本的 Firefox。我认为它也适用于 Safari 和 Opera(但不是 100% 肯定)。可能不适用于IE。

但目前让所有浏览器都能正常工作会有点复杂。

于 2012-10-12T20:05:21.883 回答