0

Нужно одновременно отправить json с полем userId и file на сервер. На стороне клиента используется библиотека 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})

Довольно много написано о том, как парсить стандартную часть с файлом

files[0].filename 
files[0].read()

Но как при этом распарсить часть с JSON ?

1 ответ 1

1

Можно не использовать Blob.

Клиент:

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})

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.