Search code examples
pythonrestflask

Flask upload: How to get file name?


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?


Solution

  • 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>
        '''