2

I'm making an app that uses React on the front and Flask/Python on the server side. I want to allow the user to upload images and then have those images committed to the DB. I'm trying to use BYTEA to store the images in the DB. This is the table structure:

class Items(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    item_description = db.Column(db.String(640))
    item_name = db.Column(db.String(60))
    username = db.Column(db.String(120))
    item_pic = db.Column(BYTEA)
    date = db.Column(db.Date, default=datetime.datetime.utcnow)
    price = db.Column(db.Float)

This is the part of the form to upload images with React:

                 <div className="flex text-sm text-gray-600">
                   <label
                     htmlFor="file_upload"
                     className="relative cursor-pointer bg-white rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500"
                   >
                     <span>Upload a file</span>
                     <input 
                      id="file_upload" 
                      name="file_upload" 
                      type="file" 
                      className="sr-only" 
                      onChange={handleInputs}
                      value={product.file_upload}
                      />
                   </label>
                   <p className="pl-1">or drag and drop</p>
                 </div>

This is how i'm sending the data to the Flask server:

function onClickSave() {
  const requestData = { 
    company_website: product.company_website, 
    price: product.price, 
    about: product.about,
    file_upload: product.file_upload,
  };

  fetch('/save_product', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(requestData),
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
    });
}

The question that I have is how would I go about converting an uploaded image into BYTEA format? Would that process be done in React or Flask?

These are some of the posts I've gone over but they don't answer what I need:

Insert an image in postgresql database

NOTE: I'm using BYTEA and not BLOB as this post recommends it for postgreSQL Storing Images in PostgreSQL

Python (flask) BLOB image, SQLite, Sqlalchemy - display image

trufflewaffle
  • 179
  • 10

0 Answers0