16

A client is sending files with arbitrary names. I am handling the request with the following implementation.

@app.route('/', methods=['GET', 'POST'])
  def upload_file():
    if request.method == 'POST':
     # 'file-name' is the file name here
     if 'file-name' not in request.files:
        flash('No file part')
        return 'no file found'
     file = request.files['file-name']

Should I ask another query/path parameter which defines the file name?

1
  • 1
    If file is successfully set in the last line, you should be able to retrieve the filename (as it was on the client's machine) with file.filename.
    – jedwards
    Sep 10, 2017 at 1:28

1 Answer 1

29

Once you fetch the actual file with file = request.files['file'], you can get the filename with file.filename.

The documentation provides the following complete example. (Note that 'file' is not the filename; it's the name of the form field containing the file.)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''
1
  • 1
    why does file.filename give me the URL path instead of the file name :-/ ?
    – Rivenfall
    Apr 6, 2020 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.