Axios 烧瓶。解析 fileblob 和 json

Axios Flask. Parsing fileblob and json

我们需要同时发送json with userIdfile到服务器。 对于客户端,使用 Axios 库。

 const userId = this.$store.getters['login/userId'];
                const obj = {
                    userId: userId
                };
                const json = JSON.stringify(obj);
                const blob = new Blob([json], {
                    type: 'application/json'
                });
                const fd = new FormData();
                const vue = this;
                async function submitAllFiles(){
                    let file = vue.files[0];
                        fd.append('file', file);
                        fd.append(userId, blob);
                        const options = {
                            onUploadProgress: (progressEvent) => {
                                ...
                            }
                        };

                        await vue.axios
                            .post('http://127.0.0.1:5000/upload_to_db', fd, options)
                            .then((response) => {
                                console.log(response);
                            }) 

这是处理的服务器部分

@api.route('/upload_to_db', methods=['POST'])
@cross_origin()
def upload_to_db():
    print('Trying to upload file')
    print(request.files)

    teacher_id = request.files.getlist('userId')

    # teacher_id = json.load(request.files['userId'])

    # print(teacher_id.get('blob'))

    files = request.files.getlist('file')
    print(files)
    if insert_pdf_into_table(teacher_id,
                             files[0]):
        return jsonify({'result': True})
    # print('Sending request to /simple_check')
    return jsonify({'result': False})

因为我们可以很容易地用标准文件[0].文件名和文件[0].read()解析文件部分 但是我们如何解析 json-part 呢?

您不需要使用 Blob。只需附加到 formData 对象。

客户端:

const userId = this.$store.getters['login/userId'];
                const fd = new FormData();
                const vue = this;
                async function submitAllFiles(){
                    let file = vue.files[0];
                        fd.append('file', file);
                        fd.append(userId, userId);
                        const options = {
                            onUploadProgress: (progressEvent) => {
                                ...
                            }
                        };

                        await vue.axios
                            .post('http://127.0.0.1:5000/upload_to_db', fd, options)
                            .then((response) => {
                                console.log(response);
                            }) 

服务器端:

@api.route('/upload_to_db', methods=['POST'])
@cross_origin()
def upload_to_db():
    user_id = request.form.get('userId')
    files = request.files.getlist('file')

    if insert_pdf_into_table(
            user_id=user_id,
            filename=files[0]):
        return jsonify({'result': True})
    return jsonify({'result': False})