How to Upload an Image and Save It in Database

how to upload the images and save it to database using react

Use multer for images upload.
Check out this article for code examples.

How to upload an image and save it in database?

For the file upload part, you need to set enctype="multipart/form-data" on the HTML form so that the webbrowser will send the file content and you'd like to use request.getPart() in servlet's doPost() method to get the file as an InputStream. For a concrete code example, see also How to upload files to server using JSP/Servlet?

Then, to save this InputStream in the DB, just use PreparedStatement#setBinaryStream() on a BLOB/varbinary/bytea column or whatever column represents "binary data" in your favorite DB engine.

preparedStatement = connection.prepareStatement("INSERT INTO user (name, email, logo) VALUES (?, ?, ?)");
preparedStatement.setString(1, name);
preparedStatement.setString(2, email);
preparedStatement.setBinaryStream(3, logo);
// ...

You don't necessarily need to convert this InputStream to byte[], it would not have been memory efficient either. Imagine that 100 user simultaneously upload images of 10MB, then 1GB of server memory would have been allocated at that point.

how to insert an image file into database table

2 possibilites:

1 Save to file server(prefered):

Save the image on your file server and save the path where you saved it in the database. This allows you to directly access this file and helps you to better output it to the user than with the second method. I'd prefer this.

Explanation: upload file with php and save path to sql

2 Save to database:

You can save the content of images to a BLOB (Binary large object).

Explanation: Insert Blobs in MySql databases with php

Image Upload takes a lot of time to save in database

I will suggest you not to store the image in database. Instead you can save the image in your server and you can store the path of the image in database. Or else you can also use Azure Blob storage to save the image.

How to upload an image and save it to database in Codeigniter?

It's very simple to achieve this with CodeIgniter.

I'll use the Version 3.1.0 reference:

View:

<?php echo form_open_multipart('upload/do_upload');?>

<input type="file" name="userfile" size="20" />

<br /><br />

<input type="submit" value="upload" />

</form>

Controller:

 public function do_upload() {

$fileData = array();
// File upload script
$this->upload->initialize(array(
'upload_path' => './uploads/',
'overwrite' => false,
'max_filename' => 300,
'encrypt_name' => true,
'remove_spaces' => true,
'allowed_types' => 'gif|jpg|png',
'max_size' => 100,
'xss_clean' => true,
));

$this->form_validation->set_rules('title', 'Title', 'required|min_length[2]');
$this->form_validation->set_rules('body', 'Body', 'required|min_length[2]');

if ($this->form_validation->run() == TRUE) {

if ($this->upload->do_upload('userfile')) {

$data = $this->upload->data(); // Get the file data
$fileData[] = $data; // It's an array with many data
// Interate throught the data to work with them
foreach ($fileData as $file) {
$file_data = $file;
}

var_dump($file_data);

$this->db->insert('entries', array(
// So you can work with the values, like:
'title' => $this->input->post('title', true), // TRUE is XSS protection
'body' => $this->input->post('body', true),
'file_name' => $file_data['file_name'],
'file_ext' => $file_data['file_ext'],
));

$this->session->set_flashdata('success', 'Form submitted successfully');
redirect('admin/add');
} else {
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('admin/add');
}
} else {
$this->session->set_flashdata('error', validation_errors());
redirect('admin/add');
}
}

You can use var_dump to see available data to work, or see the documentation (on the bottom)

https://www.codeigniter.com/userguide3/libraries/file_uploading.html

How to upload image and save url in database?

Try, to work out this w3schools tutorial step by step. Take your time and don't rush things. Take a brake, if you feel overwhelmed and try again later. I did it in 30 minutes, when i cleared my brain.

images not uploading to database but saving to folder

i have since resolved this problem myself and would like to share for anyone of similar predicament... there were several distinct problems. well, i the errors i was receiving were seemingly erroneous. the errors were with respect to the portion of the script that was responsible for uploading the images from the client to the hdd of the server. the script was properly uploading and saving the images, however the errors i was getting were fixed when i removed uneccessary portions of the path.

the main problem was with the query, uploading the image url to the table, that wasnt happening at all. this was all corrected when i re-wrote the query. see all code below.

<?php

$check_pic = mysqli_query($connection,"SELECT profile_pic FROM users WHERE username='$username'");
$get_pic_row = mysqli_fetch_assoc($check_pic);
$profile_pic_db = $get_pic_row['profile_pic'];
if ($profile_pic_db == "") {
$profile_pic = "images/default_pic.jpg";
}
else
{
$profile_pic = "userdata/profile_pics/".$profile_pic_db;
}

//script for uploading profile photo to hard disk

if (isset($_FILES['profilepic'])) {
if ((@$_FILES["profilepic"]["type"]=="image/jpeg")) {

$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rand_dir_name = substr(str_shuffle($chars), 0, 15);
mkdir("userdata/profile_pics/$rand_dir_name");

if (file_exists("userdata/profile_pics/$rand_dir_name/".@$_FILES["profilepic"]["name"]))
{
echo @$_FILES["profilepic"]["name"]." Already exists";
}
else
{
move_uploaded_file(@$_FILES["profilepic"]["tmp_name"],"userdata/profile_pics/$rand_dir_name/".$_FILES["profilepic"]["name"]);

//update table with url for photo

$profile_pic_loc = "$rand_dir_name/".@$_FILES["profilepic"]["name"];

$profile_pic_query = mysqli_query($connection, "UPDATE users SET profile_pic='$profile_pic_loc' WHERE username='$username'");

if ($profile_pic_query) {

header("Location: profile.php");
}

else
{
die('failure');
}
}
}
}

echo "

<div>
<p>UPLOAD PROFILE PHOTO:</p>
<form action='profile.php' method='POST' enctype='multipart/form-data'>
<img src='$profile_pic' width='70' />
<input type='file' name='profilepic' /><br />
<input type='submit' name='uploadpic' value='Upload Image'>
</form>
</div>
";

?>

changing;

mkdir("C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name");

if (file_exists("C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name/".@$_FILES["profilepic"]["name"]))

and;

move_uploaded_file(@$_FILES["profilepic"]["tmp_name"],"C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name/".$_FILES["profilepic"]["name"]);

to;

mkdir("userdata/profile_pics/$rand_dir_name");

if (file_exists("userdata/profile_pics/$rand_dir_name/".@$_FILES["profilepic"]["name"]))
{

and;

move_uploaded_file(@$_FILES["profilepic"]["tmp_name"],"userdata/profile_pics/$rand_dir_name/".$_FILES["profilepic"]["name"]);

corrected all the erroneous errors about 'filed to open file stream' and what not... although i still dont know what that means.

also correcting the query to;

$profile_pic_loc = "$rand_dir_name/".@$_FILES["profilepic"]["name"];

$profile_pic_query = mysqli_query($connection, "UPDATE users SET profile_pic='$profile_pic_loc' WHERE username='$username'");

if ($profile_pic_query) {

header("Location: profile.php");
}

else
{
die('failure');
}

successfully inserted the image URL into the table. works like a champ now.

How to upload image and save path to database?

After some hours I found a solution. It works. Although I would still be happy to find a second solution (according to the code I first posted here). Here is the second solution :

form page :

<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>

insert to database page :

<?php

include 'conf.php';

if ($_FILES["image"]["error"] > 0)
{
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
}
else
{
move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);
echo"<font size = '5'><font color=\"#0CF44A\">SAVED<br>";

$file="images/".$_FILES["image"]["name"];
$sql="INSERT INTO eikones (auxon, path) VALUES ('','$file')";

if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "<font size = '5'><font color=\"#0CF44A\">SAVED TO DATABASE";

}

mysql_close();

?>


Related Topics



Leave a reply



Submit