0

This is my upload function but every time I go to addclothes route and adding image into the form then I got this error: this is the error

I know is my path problem but I don't know how to put the file in the base directory

@app.route('/addclothes', methods=["POST","GET"])
def addclothes():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']

        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file :
            filename = secure_filename(file.filename)
            file.save(os.path.join('/static/img/',filename))

            new_clothes = Clothes(clothesname=clothesname,image=image,price=price,isSuperUser=False)
            db.session.add(new_clother)
            db.session.commit()
            
            return redirect(url_for('addclothes'))



    return render_template('addclothes.html')

This is my file structure:

file structure

I want to add it to base directory

Parzival
  • 2,051
  • 4
  • 14
  • 32

1 Answers1

0

You should save this with:

file.save(os.path.join('static/img/',filename))

Note the removal of the preceding / before static. With this present it is trying to save to a static subdirectory on the / drive of the server, not within the app's directory.

On a side note, it may be to your advantage to make a filename containing random characters, rather than using the user-provided filename; certainly if you're handling a large number of file uploads. See another thread I wrote regarding avoiding duplicate filenames.

v25
  • 7,096
  • 2
  • 20
  • 36
  • Thanks you so much It helps me a lot. You save my life(This question have border me a whole day!!!). – Kenneth Lau Apr 09 '21 at 17:28
  • @KennethLau No problem. If this solved your issue, please consider marking the answer as accepted. – v25 Apr 09 '21 at 17:33