保存文件为BLOB数据库阿贾克斯PHP PDO [英] Saving Files as blob in database ajax php pdo

查看:224
本文介绍了保存文件为BLOB数据库阿贾克斯PHP PDO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ fileCount =计数($ _ FILES);
为($ i = 0; $ I< $ fileCount; $ I ++){
    $计划生育=的fopen($ _ FILES [文件_$ I] ['tmp_name的值'],RB);
    $ stmt4 = $胸径 - > prepare(INSERT INTO files_tbl(销,言论,fileblob,FILE_TYPE,nameoffile,文件大小)VALUES(,,,,,)??????);
    $ stmt4  - > bindValue(1,$针,PDO :: PARAM_STR);
    $ stmt4  - > bindValue(2,$言论,PDO :: PARAM_STR);
    $ stmt4  - > bindParam(3,$ FP,PDO :: PARAM_LOB);
    $ stmt4  - > bindParam(4,$ _FILES [文件_$ I] ['类型'],PDO :: PARAM_STR);
    $ stmt4  - > bindValue(5,$ _FILES [文件_$ I] ['名称'],PDO :: PARAM_STR);
    $ stmt4  - > bindValue(6,$ _FILES [文件_$ I] ['大小'],PDO :: PARAM_STR);
    $ stmt4  - >执行();
}
 

这是我如何插入文件的blob在PHP。它被保存一个文件,但它是不保存正​​常。当我说这是不正确的节约我的意思是是前进的道路上是错误的。当我比较使用我的项目在保存文件并手动添加在XAMPP文件中有fileblob例如差我保存的文件手动XAMPP的fileblob是 [BLOB - 488.9昆明植物研究所] 当我使用该项目成为 [BLOB - 479.2昆明植物研究所] 。我觉得这个原因,当我试图表明,从数据库,它显示一个空白页的文件(当我告诉该文件是我插入使用项目中的文件),但如果我试图表明该文件是我手动插入XAMPP文件它显示该文件。

还有什么比我的插入是错误的?为什么我不能保存正确的BLOB

更新

 <输入类型=文件ID =filecontentNAME =filecontent多=>
 

AJAX

  var文件= $('#filecontent')[0] .files;
对于(VAR I = 0; I< file.length;我++){
    formData.append(_文件+ I,文件[I]);

    //更多的数据传递给FORMDATA
    //formData.append("file,文件[I]);
    的console.log(文件[I]);
}

$阿贾克斯({
    网址:../include/AddNew.php,
    键入:POST,
    数据类型:JSON,
    数据:FORMDATA,
    过程数据:假的,//告诉jQuery的不处理数据
    的contentType:假的,//告诉jQuery的不要设置的contentType
    成功:功能(数据){
        的console.log(数据);
        警报(data.message);
        //window.location.reload(true);
    },
    错误:功能(数据){
        //警报(错误!); //可选
    }
});
 

更新

当我试图把的print_r($ _ FILES); 前行为($ i = 0; $ I< $ fileCount; $ I ++){输出

 阵列
(
    [file_0] =>排列
        (
            [名] => whomovedmycheese  -  Copy.pdf
            [类型] =>应用程序/ PDF格式
            [tmp_name的值] => C:\ Users \用户HogRider \ XAMPP的\ TMP \ phpE775.tmp
            [错误] => 0
            [大小] => 500624
        )

    [file_1] =>排列
        (
            [名] => whomovedmycheese.pdf
            [类型] =>应用程序/ PDF格式
            [tmp_name的值] => C:\ Users \用户HogRider \ XAMPP的\ TMP \ phpE786.tmp
            [错误] => 0
            [大小] => 500624
        )

)
 

更新

解决方案

按<一个href="http://stackoverflow.com/questions/6346319/php-pdo-mysql-inserting-into-mediumblob-stores-bad-data">PHP/PDO/MySQL:插入MEDIUMBLOB商店坏数据,请尝试使用以下行来构建你的PDO对象:

  $胸径=新PDO($ DSN,$的用户名,密码$,数组(PDO :: MYSQL_ATTR_INIT_COMMAND =&gt;中集名处理latin1 COLLATE latin1_general_ci));
 

说明

我觉得有,本·M在链接的问题指出,在这里工作的两个坏的设计决策。

有一个连接字符集的概念。这个想法是,SQL文本可以在任何字符集并且在检索由SQL服务器,然后转换

这不工作那么好二进制数据,因为它不是文本,因此,不能根据定义,在任何字符集,,但使用字符串

这个问题可以通过传输过程中引用BLOB数据(使用的BASE64_ *功能或通过的十六进制转义),而事实上,这是很多人都在做。

第二个设计决定是PDO / PHP:PDO不进行任何字符集转换(它不能,因为在PHP中的字符串是天生的字符集无关的),所以PHP是唯一的(或少数语言之一),其中在SQL传递字符集的选择其实很重要,因为它需要匹配的编码输入字符串其实是在

在其他语言中,转移字符集只是需要EX pressive足以涵盖可能在字符串中使用任何字符。在今天的世界emojis的,这一点,最有可能仅通过单向code字符集(UTF-8等)保证。但是,的这些都不是二进制安全的(以字节为单位的,不是每一个可能的组合会产生一个有效的字符串),所以即使我们能解决的PHP问题,我们还是会留下的问题# 1。

在一个理想的世界,SQL命令将始终处于转移和每一个字符串值在ASCII字符将有一个字符集的说法,其中的二进制可能是一个可能值,其附带。 MySQL的居然有这样的结构对于字符串,它所说的介绍人。 4.1.x或更高版本,但似乎并没有一个有效的价值。

该字符集信息将被用于由另一端将字符串值转换成其本地字符集(或列的客户端 - 服务器转移或编程语言的字符串的字符集为服务器到客户端的传输)。

这样的话,这将有BLOB值进行转义的唯一的事情是字符串分隔符()。

$fileCount = count($_FILES);
for ($i = 0; $i < $fileCount; $i++) {
    $fp = fopen($_FILES["file_".$i]['tmp_name'], 'rb');
    $stmt4 = $dbh - > prepare("INSERT INTO files_tbl (pin,remarks,fileblob,file_type,nameoffile,filesize) VALUES (?,?,?,?,?,?)");
    $stmt4 - > bindValue(1, $pin, PDO::PARAM_STR);
    $stmt4 - > bindValue(2, $remarks, PDO::PARAM_STR);
    $stmt4 - > bindParam(3, $fp, PDO::PARAM_LOB);
    $stmt4 - > bindParam(4, $_FILES["file_".$i]['type'], PDO::PARAM_STR);
    $stmt4 - > bindValue(5, $_FILES["file_".$i]['name'], PDO::PARAM_STR);
    $stmt4 - > bindValue(6, $_FILES["file_".$i]['size'], PDO::PARAM_STR);
    $stmt4 - > execute();
}

This is how i insert file as blob in php. It is saving a file but it is not saving properly. When i say it is not saving properly i mean something is wrong along the way. When i compare saving the file using my project and manually adding the file in XAMPP there is a difference in fileblob for example i save a file manually in xampp the fileblob is [BLOB - 488.9 KiB] when i use the project is becomes [BLOB - 479.2 KiB]. I think this the reason when i try to show the file from database it is showing a blank page(when the file i show is the file i insert using project) but if the file i try to show is the file i insert manually in xampp it is showing the file.

What could be wrong in my insert?why am i not saving the proper blob

UPDATE

<input type="file" id="filecontent" name="filecontent" multiple="">

ajax

    var file = $('#filecontent')[0].files;
for (var i = 0; i < file.length; i++) {
    formData.append("file_" + i, file[i]);

    //more data are passed to formData
    //formData.append("file", file[i]);
    console.log(file[i]);
}

$.ajax({
    url: '../include/AddNew.php',
    type: 'POST',
    dataType: "json",
    data: formData,
    processData: false, // tell jQuery not to process the data
    contentType: false, // tell jQuery not to set contentType
    success: function(data) {
        console.log(data);
        alert(data.message);
        //window.location.reload(true);
    },
    error: function(data) {
        //alert("Error!"); // Optional
    }
});

UPDATE

when i tried to put print_r($_FILES); before the line for ($i = 0; $i < $fileCount; $i++) { the output is

Array
(
    [file_0] => Array
        (
            [name] => whomovedmycheese - Copy.pdf
            [type] => application/pdf
            [tmp_name] => C:\Users\HogRider\xampp\tmp\phpE775.tmp
            [error] => 0
            [size] => 500624
        )

    [file_1] => Array
        (
            [name] => whomovedmycheese.pdf
            [type] => application/pdf
            [tmp_name] => C:\Users\HogRider\xampp\tmp\phpE786.tmp
            [error] => 0
            [size] => 500624
        )

)

UPDATE

解决方案

As per PHP/PDO/MySQL: inserting into MEDIUMBLOB stores bad data, try using the following line to construct your PDO object:

$dbh = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES latin1 COLLATE latin1_general_ci"));

Explanation

I think there are, as Ben M notes in the linked question, two bad design decisions at work here.

There is this concept of a connection charset. The idea is that the SQL text can be in any charset and is then converted upon retrieval by the SQL server.

This does not work that well with binary data as it is not text and, thus, must not, by definition, be in any charset, but is still transferred using string literals.

This issue can be worked around by quoting BLOB data during transfer (either using the BASE64_* functions or by hex-escaping) and, indeed, that is what many people are doing.

The second design decision is in PDO/PHP: PDO does not do any charset conversion (it can’t, because strings in PHP are inherently charset-agnostic) so PHP is the only (or one of the few languages) where the choice of the SQL transfer charset is actually important because it needs to match the encoding the input strings are actually in.

In other languages, the transfer charset just needs to be expressive enough to encompass any characters that might be used in strings. In today’s world of emojis, this, most likely is only guaranteed by unicode charsets (utf-8 and the like). However, none of these are binary-safe (in that not every possible combination of bytes yields a valid string) so even if we could work around the PHP issue, we’d still be left with problem #1.

In an ideal world, SQL commands would always be in the ASCII charset during transfer and every string value would have a charset argument, of which "binary" could be a possible value, supplied with it. MySQL actually has such a construct for strings, which it calls an "introducer". "_binary", however, does not seem to be a valid value.

This charset information would then be used by the other end to convert the string value into its the native charset (either the column’s for client-to-server transfers or the programming language’s string charset for server-to-client transfers).

That way, the only thing that would have to be escaped in BLOB values would be the string delimiter (" or ').

这篇关于保存文件为BLOB数据库阿贾克斯PHP PDO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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