'how to upload binary image to sql server using php laravel
As far as I know, uploading images to databases is wrong, but in this specific issue, I have to upload images to SQL Server
. I found some results, for example using the base64
string.
My database structure contains a lot of images with type of image
in SQL Server
.
Since I'm unfamiliar with SQL server, I'm using Laravel 5.4 for connecting to databases.
The problem now is this.
How can I upload an image to SQL Server(colomn type:
binary image
) using php in laravel?
What is the best way to display this image?
Solution 1:[1]
You can save the image to a temp location then read it into a var with file_get_contents() then insert it into your database column (needs to be binary blob or something similar). To display it you can use a route like this:
Route::get('images/{id}', function($id)
{
$image = Images::find($id);
$image = Response::make($image->content, 200);
$image->header('Content-Type', 'image/jpeg');
return $image;
});
This assumes you are using Eloquent for dealing with your DB.
Tested this using help from here: https://laravel.io/forum/02-17-2014-how-do-you-save-image-to-database-and-display-it-on-website
Solution 2:[2]
My answer is bit messy, as Eloquent doesn't support Image BLOB to SQL Server, so the concept is we treat the image as param to SQLSrv driver based on PHP PDO load image into MS SQL Server 2012 , then we can upload it using bare PDO SQLSrv using BindParam.
example
Route::post("/example", function(Request $request) {
/** @var \PDO $db */
$db = DB::connection("sqlsrv")->getPdo();
$stmt = $db->prepare("INSERT INTO gambar VALUES(:id, :gambar)");
$stmt->bindValue("id", $request->input("angka"), PDO::PARAM_INT);
$gambar = $request->file("gambar")->getContent();
$stmt->bindParam("gambar", $gambar,
PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
// $stmt->bindValue("gambar", $request->file("gambar")->getContent(),
// PDO::PARAM_LOB);
dd($stmt->execute());
});
It's quite messy, as I can't use the built in Eloquent ORM, sad... noises...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | OneLiner |
Solution 2 |