This is the first day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Hello everyone, I am Brother Chen ~

Chen brother recently used his spare time to write an online visualization platform. In the process, he also found some technologies interesting, so he shared them in a modular form. For example, upload files from the web interface (front end) to the server (back end).

Take a look at the interface diagram of this module:

Click the “Upload Excel file” button, select the Excel file, you can preview it online, and the back end will receive and save it to the server. This article is mainly about sharing the content of the uploaded file.

Background: The front end is HTML, and the back end uses Flask framework. Click on the front end to upload an Excel file, and the back end receives and saves it locally.

01 Front-end Processing

1. File selection box

As anyone who has written HTML code knows, the easiest way to upload a file control is by default (without using a plug-in).

<input id="file"  name="loadfile"  type="file">
Copy the code

File select box id is file, type is file, using the ID to call js asynchronous code, type is input is selected local file.

This defines a file selection box.

2. Asynchronous Ajax processing

Before you can use Ajax asynchrony, you need to introduce Jquery files

<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
Copy the code

Asynchronous code:

$('#file').change(function (e) {
     var files = e.target.files;
     var formFile = new FormData();
     formFile.append("file", files[0]); // Add file objects
      $.ajax({
         url: "/upload_file".data: formFile,
         type: "post".dataType: "json".cache: false.// Upload files without caching
         processData: false.// Used to serialize the data argument
         contentType: false./ / must
         success: function (result) {
             alert("Upload done!"); }})});Copy the code

Click the “Upload Excel file” button on the web page. After selecting the Excel file, the above JS code is automatically triggered (id: file is used to trigger the specified JS code).

Brief introduction:

(1) e.targo. files: Select the file to upload

(2) FormData: Encapsulate the uploaded file into FormData

(3) /upload_file: back-end upload interface (entry for receiving files)

The function of this JS code is to upload the selected Excel file to the back-end interface: /upload_file. After the back-end processing, the response value is returned: result, and the page prompts: the upload is complete.

02 Back-end processing

The back end uses Python to write, with the Flask framework, if you do not understand the simple use of Flask, can refer to a previous article: Flask with ECharts to achieve online visualization, super detailed!

Here Chen elder brother directly take you to see the back-end interface, detailed complete source code, Chen elder brother will be directly given at the end of the article.

# upload file
@app.route('/upload_file', methods=['POST'])
def upload() :
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)  # Path where the current file is located
        print(f.filename)
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        # Milliseconds timestamp
        file_name = str(round(time.time() * 1000))
        dir = str(time.strftime('%y%m%d', time.localtime()))
        upload_path = os.path.join(basepath, 'uploads/'+dir)
        Check whether the folder exists
        if not os.path.exists(upload_path):
            os.mkdir(upload_path)
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        file_path = str(file_name)+str(f.filename)
        f.save(upload_path+"/"+file_path)
    return Response(json.dumps(file_path), mimetype='application/json')
Copy the code

Brief description:

(1) The interface name is /upload_file and the request mode is POST.

(2) request. Files [‘file’] : receive uploaded files;

(3) Line 6~16: Automatically create a folder named after the current date in the upload folder as the storage path to save the uploaded file;

(4) file_name: is the current millisecond time stamp, rename the uploaded file: timestamp + original file name;

(5) Response returns the file path to the front-end asynchronous processing function success: file_path;

03 effect

When both the front and back ends are processed, start debugging the program. Let’s see what happens.

So that’s what front-end Ajax asynchronously uploads files to the back end.

Full source address:

wwi.lanzoui.com/imM6bs2f44d

Finally say: the original is not easy, ask to give a praise!