Search code examples
flaskflask-restfulflask-mysql

I am not able to delete image but insert in working fine with same directory using Flask


i am trying to remove image from a folder but it was not working giving a error : FileNotFoundError: [WinError 2] The system cannot find the file specified: 'static\images\2018194259_a476v_engelhart-tilburg_inside-track_text_font_product.jpg'

But insert is working very fine with same upload directory

UPLOAD_FOLDER = 'static\images'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

insert code :

def insert():
cursor = db.cursor()

if request.method == "POST":
    flash("Data Inserted Successfully")
    name = request.form['name']
    email = request.form['email']
    phone = request.form['phone']

    image = request.files['imgfile'] #myfile is name of input tag

    if image and allowed_file(image.filename):
        fileTemp = secure_filename(image.filename)
        time_p = time.strftime('%Y%H%M%S')

        filename = time_p+"_"+fileTemp

        image.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))

        path = filename
    empty=''
    if path is empty:
        return "You have not uploading a image"
    else:
        cursor.execute("INSERT INTO student_flask (name, email, phone)VALUES (%s, %s, %s)", (name, path, phone))
        db.commit()
        cursor.close()

    return redirect(url_for('Index'))

Remove IMAGE Code:

@app.route('/delete/<string:id_data>', methods = ['GET'])
def delete(id_data):

   imgname = image_name(id_data)
   mna = imgname[0]
   os.remove(os.path.join(app.config['UPLOAD_FOLDER'], mna))
   return redirect(url_for('Index'))

Solution

  • Query the DB to get the image's name first. If it's an object by itself .i.e. Image.name or an object attribute .i.e. Foo.image. In your delete function you must run commit for the changes to take effect. Also the id should be an int:

    @app.route('/delete/<int:id>', methods=['GET', 'POST'])
    def delete(id=None):