我正在尝试通过上传的文件base64将图像保存为我的ORACLE 11g R2数据库中的BLOB,但是当我从DB检索此文件时,它不会显示带有base64_encode功能的图像。当我从SQL Developer下载此文件时,该文件也不是图像,只有一条消息说该图像无效或已损坏。我的问题详情如下: 我在我的网页上有这个表格: Upload Page 1
“+”按钮是一个文件输入,点击后,用户可以选择一个或多个要上传的文件,这些文件会在预览中显示,如下所示: Upload Page 2
用户可以打开文件输入,选择他想要的图像数量,关闭文件输入并重新打开它以添加更多文件他想要多少次。对于添加的每个文件,javascript创建预览并将base64设置为“a”元素的href,如下所示:
//create preview
$("#exams-fileinput").on('change',function(e){
var input = $(this);
var files = input.prop('files');
var countFiles = files.length;//alert(files.length);
if (window.File && window.FileReader){
var allow = /png|jpg|jpeg|tiff|pdf$/i;
// com suporte a FileReader()
for(i= 0;i <countFiles; i++){
file = files[i];
if(!allow.test(file.name)){continue;}
imageType = /image.*/;
reader = new FileReader();
reader.onload = function(e){
filePreview = e.target;
var fileName = file.name;
var fileResult = filePreview.result;
var fileThumb = file.type.match(imageType) ? fileResult : 'assets/img/file-document.png'; // https://cdn4.iconfinder.com/data/icons/office-20/128/OFFice-51-256.png assets/img/file-document.png
var classIframe = file.type.match(imageType) ? '' : 'fancybox.iframe';
var imgPrevContent =
'<div name="file-added" class="col-xs-6 col-sm-4 col-md-3 ms-file-thumbnail-preview-item" >'+ '<a href="'+fileResult+'" class="ms-filedata fancybox '+classIframe+'" rel="exam" data-type="img" data-file-name="'+fileName+'">'+ //<= aqui vai entrar o "fancybox.iframe", se necessário <= Vamos obter daqui o código do arquivo para subir ".ms-filedata"
'<figure class="img-responsive img-thumbnail" style="background-image:url('+fileThumb+');">'+
'<figcaption>'+
'<p><i class="fa fa-eye fa-3x"></i><p>'+
'<p class="ms-ellipsis">'+fileName+'</p>'+
'</figcaption>'+
'</figure>'+
'</a>'+
'<input type="file" value="'+fileResult+'" id="" style="display: none;">'+
'</div>';
console.log('Nome do arquivo: '+fileName+' - Tamanho: '+ file.size+' - HTML: '+imgPrevContent.length);
fileName='';
$("#exam-view-files").append(imgPrevContent);
};
reader.readAsDataURL(file);
}
}else{
// browser doesn't supor file reader
}
});
当用户点击保存按钮“Salvar”时,我将ajax添加和发送的所有base64文件保存到我的ORACLE 11g R2数据库的BLOB字段中,如下所示:
//save function
$("#btn-save-files").click(function(e){
var filesToAdd = [];
$("div[name=file-added]").each(function(e){
filesToAdd.push({
content: $(this).children("a").attr("href"),
name: $(this).children("a").data("file-name")
});
});
$.ajax({
type: 'POST',
url: 'controller/ctrl-person-profile-action.php',
data: { action: "insertfiles",
files: filesToAdd
},
datatype: "json",
async: true,
success: function(response){
response = JSON.parse(response);
switch(response["status"].toLowerCase()){
case "success": swal("Pronto", "Adicionado com sucesso", "success");
break;
case "fail": swal("Atenção", response["message"], "warning");
break;
default: swal("Ops..", "Ocorreu um erro inesperado ao inserir o medicamento", "error");
break;
}
}
});
}
然后拿这些文件并通过PHP保存,如下所示:
//Ajax calls this function
function InsertFiles(){
$files = isset($_REQUEST['files']) ? $_REQUEST['files'] : null;
foreach ($files as $file) {
$fileBase64 = explode(",", explode(";", $file["content"])[1])[1];
$fileType = explode(":",(explode(";", $file["content"])[0]))[1];
$fileInsert = new MyFileClass();
$fileInsert->setFile($fileBase64);
$fileInsert->setType($fileType);
$fileInsert->Insert();
}
//Class MyFile method insert:
public function Insert(){
$sql = "INSERT FILES (ID,
MIME_TYPE,
FILE)
VALUES(SEQ_FILES.NEXTVAL,
'$this->type,
EMPTY_BLOB()
) RETURNING FILE INTO :file";
$conn = GetDBConnection();
$statment = oci_parse($conn, $sql)
// Creates an "empty" OCI-Lob object to bind to the locator
$fileBlob = oci_new_descriptor($conn, OCI_DTYPE_LOB);
// Bind the returned Oracle LOB locator to the PHP LOB object
oci_bind_by_name($statment, ":file", $fileBlob, -1, OCI_B_BLOB);
// Execute the statement using , OCI_DEFAULT - as a transaction
oci_execute($statment, OCI_DEFAULT)
or die ("Erro execute SQL command");
// Now save a value to the LOB
if (!$fileBlob->save('INSERT: '.base64_decode($this->file))) {
// On error, rollback the transaction
oci_rollback($conn);
die("Erro execute SQL command");
} else {
// On success, commit the transaction
oci_commit($conn);
}
// Free resources
oci_free_statement($statment);
$fileBlob->free();
//feca conexão
oci_close($conn);
}
有人可以帮我把这个base64文件保存到ORACLE上的BLOB字段并从我的BLOB中检索一个有效的文件吗?
很多!
答案 0 :(得分:0)
I found solution by my self just adjusting my insert function, removing 'INSERT: ' string from blob save function, like below:
Before:
// Now save a value to the LOB
if (!$fileBlob->save('INSERT: '.base64_decode($this->file))) {
// On error, rollback the transaction
oci_rollback($conn);
die("Erro execute SQL command");
} else {
// On success, commit the transaction
oci_commit($conn);
}
After:
// Now save a value to the LOB
if (!$fileBlob->save(base64_decode($this->file))) {
// On error, rollback the transaction
oci_rollback($conn);
die("Erro execute SQL command");
} else {
// On success, commit the transaction
oci_commit($conn);
}
Thx again! I hope it can be usefull for someone one day! :)