MySQLi. Upload and save image file as BLOB. PostFile. PostText

You are using a PatchFile and Get request at the same time, which does not make sense
Taifun

Hi there !
Did you find a solution for this ? Are phones prevented from doing this ?

Look again carefully into the example, which was provided above

Taifun

Does that put the image in tiny DB so it can be sent to the PHP from there, and not hidden by Samsung

Wonderful ! I finally got it working. Thank you Taifun and Juan and all. The base 64 example above was the answer. Oh what was I doing ? Thank you

2 posts were split to a new topic: How do you make this PHP code write to a specific directory?

5.- Upload and save an image file as a BLOB. List of files. Download a file.

Using this code made by @TIMAI2 we can upload, list and download BLOB files in a MySQL database.

updnBlob.aia (3.8 KB)

upBlob.php
<?php
$db_host="localhost";
$db_name="xxxxxx";
$db_login="xxxx";
$db_pswd="xxxxxxxx";
$conn = new mysqli($db_host, $db_login, $db_pswd, $db_name);
$file = file_get_contents('php://input');
	if (file_put_contents($_GET['file'],$file == TRUE))  {   
		$filename = $_GET['file'];
		$extension = pathinfo($filename, PATHINFO_EXTENSION);
		$imageBlob = mysqli_real_escape_string($link, $file);
		$sql = "INSERT INTO blobData (imageBlob, extn, filename) VALUES ('$imageBlob', '$extension', '$filename')";
		if ( mysqli_query($conn, $sql)) {
		$id = mysqli_insert_id($conn);
		echo "[" . $id . ", " . $filename . "]";	
		} else {
		  echo "Error: " . mysqli_error($sql) . "<br>" . mysqli_error($conn);
		}	
		mysqli_close($conn);	
	} else {
	echo "Error getting file";  
   	}		
?>
dnBlob.php
<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxxxxxx";
$dbname = "xxxxx";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['id'];
$sql = "SELECT * FROM blobit WHERE id =" . $id;
$result = $conn->query($sql);
  list($id, $imageBlob, $extension, $filename ) = mysqli_fetch_array($result);
  header("Content-Length: " . strlen($imageBlob));
  header("Content-Type: image/" . $extension);
  header("Content-Disposition: attachment; filename=$filename");
  ob_clean();
  flush();
  echo $imageBlob;
  $link->close();
?>

1 Like

6.- Simplified code to download BLOB image.

p366_mysql_bajarBlob.aia (2.2 KB)

<?php
 // 1.- IDENTIFICACION nombre de la base, del usuario, clave y servidor
$db_host="localhost";
$db_name="id19781186_base"; // fake
$db_login="id19781186_juan";  // fake
$db_pswd="Contraseña";  // fake

// 2.- CONEXION A LA BASE DE DATOS
$link = new mysqli($db_host, $db_login, $db_pswd, $db_name);

if ($link->connect_error) {
    die("Error de conexión: ".$link->connect_error);
} else {

// 3.- OBTENER EL ARCHIVO. GET FILE.
$nombre = $_GET['imagen'];
$resultado = mysqli_query($link, "SELECT * FROM dibujos WHERE nombre = '$nombre'");
if ($resultado && mysqli_num_rows($resultado) > 0) {
    $fila = mysqli_fetch_assoc($resultado);
    $imagenBlob = $fila['imagen'];
    $extension = $fila['extension'];

// 4.- ENVIAR EL ARCHIVO. SEND FILE.
	header("Content-Type: image/".$extension);
    header("Content-Disposition: attachment; filename=$nombre.$extension");
	echo $imagenBlob;
}

mysqli_close($link);
}
?>

mysql_blob60

1 Like

Is it viable to select all the BLOB files at once from a table if it begins to get large ? If you have 1000 or more records and select them all for display - will it crash the APP - Browser. ?

An idea would be to put a clock (or two) and check the download of a file.

Would it be quicker (possible) to get the images from the file system ?

Another idea would be to have the images in the file system, a php code to compress them in .zip and download the .zip to the app. Using an extension unzip the .zip.

Resize the images before uploading as blobs. Depends on what the images are for. If thumbnails will do, then image/blob size will be less.

JQuery can limit the returned data for scrolled output.

ZIP the images folder at the host side is very interesting. Could this be done ?

Open a new topic about zip - php

Hi @Juan_Antonio ,

I've read this post and since it is still opened, I am posting here. But if it is necessary, I can open another post.

I have used your extension which was indicated by TIMAI2, and I am having a problem when I am trying to save the image in the BLOB field, in MySQL remote server. What I am doing to send the image to the server is this:

1 - I am taking the photo and saving the Base64 string in a text field on a local SQLite, like this:

image

2 - In other screen of my app, I send to the remote server:

In my PHP script, I am doing this:

$_foto = $_POST['foto'];

// Mudando alguns caracteres da foto enviada pelo aplicativo
$_foto_gravar = strtr($_foto, '-_,', '+/=');
$_foto_gravar = base64_decode($_foto_gravar);

// Salvando em arquivo pra poder gravar
//$caminho = '../tmp/'; //voltar uma pasta
$_arquivo = $caminho.session_id().mt_rand(1000000000, 1999999999).'.jpg';
file_put_contents($_arquivo,$_foto_gravar); //salvamos em DISCO
$fp = fopen($_arquivo, 'r'); //abrimos o arquivo/imagem para montar a instrução SQL
$dados_foto = fread($fp, filesize($_arquivo));
$dados_foto = addslashes($dados_foto); //importante isso
fclose($fp); //fechar arquivo/imagem

And after the UPDATE command, it stores in the MySQL BLOB field. The only problem I am facing is that the image saved in MySQL is only a black image. So, what am I doing wrong?

TIA,

I would start here:

See how Juan uses str_replace:

2 Likes

hmmm yes, @TIMAI2 . It's a good start. let's see then.

And that was the trick!!! worked perfectly!!! It's funny that this PHP script was working before, but... the important thing that it is solved!!

Thank you!!!

1 Like