Plotly AntDesign Upload Image Size Issue

Hello Everyone,

I created an app using Python Dash and Ant Design. In the Ant Design, I want the app can let the user upload images and save them to my SQLite3 database. The issue is that no matter how I set up the fileMaxSize in the “facAntPictureUpload,” it always pops out the error “The file size is too big.” Even my test image is only KB.
Anyone knows how to solve this issue?

demo_upload

import dash_ag_grid as dag
import feffery_antd_components as fac
import sqlite3
import base64
from dash import html

def create_edit_sbl_modal():
    """edit the SBL record modal

    Returns:
        _type_: _description_
    """
    # Modal for Creating New SBL
    return fac.AntdModal(
        [
            # SBA Date and Eval Date on the same row
            fac.AntdRow([
                fac.AntdCol(html.Label('SBA Date:', style={'marginRight': '10px'}), span=2),
                fac.AntdCol(fac.AntdDatePicker(id='edit-sba-date', placeholder='Select SBA Date', locale='en-us'), span=10),
                fac.AntdCol(html.Label('Eval Date:', style={'marginRight': '10px', 'marginLeft': '20px'}), span=2),
                fac.AntdCol(fac.AntdDatePicker(id='edit-eval-date', placeholder='Select Eval Date', locale='en-us'), span=10),
            ], style={'marginBottom': '10px'}),

            # Upload input for Map Image
            fac.AntdRow([
                fac.AntdCol(html.Label('Map Image:', style={'marginRight': '10px'}), span=2),
                fac.AntdCol(
                    fac.AntdPictureUpload(
                        id='edit-map-image-upload',
                        apiUrl='/upload/',
                        fileMaxSize=5,  # Max file size in MB
                        buttonContent='Click to upload map image',
                        confirmBeforeDelete=True,
                        locale='en-us',
                    ),
                    span=20
                ),
            ], style={'marginBottom': '10px'}),

            # Upload input for Trend Image
            fac.AntdRow([
                fac.AntdCol(html.Label('Trend Image:', style={'marginRight': '10px'}), span=2),
                fac.AntdCol(
                    fac.AntdPictureUpload(
                        id='edit-trend-image-upload',
                        apiUrl='/upload/',
                        fileMaxSize=5,  # Max file size in MB
                        buttonContent='Click to upload trend image',
                        confirmBeforeDelete=True,
                        locale='en-us',
                    ),
                    span=20
                ),
            ], style={'marginBottom': '10px'}),
        ],
        id='modal-edit-sbl',
        visible=False,
        title='Edit SBL Record',
        renderFooter=True,
        okText='Ok',
        cancelText='Cancel',
        width='75vw',
    )

From what you’ve provided, it seems you haven’t constructed the corresponding file upload service API. You can refer to the document section “Tips: File Upload Service Interface Example”.

import os
from flask import request

# Here, 'app' is the Dash instance
@app.server.route('/upload/', methods=['POST'])
def upload():
    '''
    Build a file upload service
    :return:
    '''

    # Get the upload ID parameter, used to point to the save path
    uploadId = request.values.get('uploadId')

    # Get the name of the uploaded file
    filename = request.files['file'].filename

    # Based on the upload ID, if it does not exist locally, the directory will be automatically created
    try:
        os.mkdir(os.path.join('custom cache root directory', uploadId))
    except FileExistsError:
        pass

    # Stream write the file to the specified directory
    with open(os.path.join('custom cache root directory', uploadId, filename), 'wb') as f:
        # Stream write large files, here 10 represents 10MB
        for chunk in iter(lambda: request.files['file'].read(1024 * 1024 * 10), b''):
            f.write(chunk)

    return {'filename': filename}

Hi echeung, Thank you for your help. In case someone face the same issue, I just upload my test file below. and it works based on your example.

import dash
from dash import html
import feffery_antd_components as fac
from dash.dependencies import Input, Output, State
import base64
from flask import request, jsonify

# Initialize the Dash app
app = dash.Dash(__name__)

# Define the layout
app.layout = html.Div([
    fac.AntdPictureUpload(
        id='picture-upload-demo',
        apiUrl='/upload/',
        buttonContent='Select Image',
        uploadId='test-picture-upload',
        locale='en-us',
        fileMaxSize=5,
    ),
    html.Div(id='upload-output')
])


# Route to handle file upload
@app.server.route('/upload/', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    
    # Read and encode file content
    file_content = file.read()
    encoded_content = base64.b64encode(file_content).decode('utf-8')
    
    # Return success response
    return jsonify({
        'status': 'success',
        'fileName': file.filename,
        'fileContent': encoded_content
    })

if __name__ == '__main__':
    app.run_server(debug=True, port=8050)```