Как узнать прогресс загрузки файла с помощью filepond? - PullRequest
0 голосов
/ 07 августа 2020

У меня есть конечная точка API, которая работает с запросом PUT для обновления информации о пользователе, например аватара пользователя. Этот API построен на Django. В моем Frontend я использую NUXT для загрузки файла с помощью FilePond, я сделал следующее:

<template>

        <section class="section">
            <div class="container">

            <file-pond
                name="test"
                ref="pond"
                label-idle="Drop files here..."
                v-bind:allow-multiple="true"
                accepted-file-types="image/jpeg, image/png"
            />

            <vs-button success @click='userinfo_put_avatar'>File upload data</vs-button>
            </div>
        </section>

</template>

<script>
import vueFilePond from 'vue-filepond';
import 'filepond/dist/filepond.min.css';
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css';
import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type';
import FilePondPluginImagePreview from 'filepond-plugin-image-preview';

let FilePond = vueFilePond(FilePondPluginFileValidateType, FilePondPluginImagePreview);

export default {
    components: {
        FilePond,
    },
    methods: {
        async userinfo_put_avatar() {
            let file = this.$refs.pond.getFiles(0) 
            let fileupload = new FormData();
            fileupload.append('avatar', file)
            let config = {
                 headers: {
                    'Content-Type': 'multipart/form-data'
                 }
            }           
            let data = await this.$axios.put('user-info/', fileupload, config);
        },
   }

};
</script>

У меня это очень хорошо работает. Но я хочу, чтобы функция Filepond показывала статус загрузки с вращающимся svg, когда в процессе загрузки и после завершения показывал зеленый статус.

Progress Completed

I tried using the pond.processFile(0) but it doesnot upload the file. I tried using the FilePond.setOptions() but it gives me an error setOptions is not a function. If this could work somehow. I would be able to overwrite onaddfileprogress event using the following code from GITHUB ISSUE LINK

FilePond.setOptions({
  instantUpload: true,
  allowImagePreview: false,
  server: {
    url: '/images',
    process: {
      url: '/upload',
    },
    revert: '/revert',
    restore: '/restore/',
    load: '/load/',
  },
  onremovefile: function(error, file) {
    if (file.serverId) {
      let input = document.createElement('input');
      input.type = 'hidden';
      input.name = 'DeletedFilepondImages';
      input.value = file.serverId;
      uploadForm.appendChild(input);
    }
  },
  onaddfilestart: function(file) {
    console.log(`onaddfilestart`);
    buttonForm.classList.add('filepondUpload');
    buttonForm.setAttribute('disabled', 'true');
  },
  onaddfileprogress(file, progress) {
    console.log(`onaddfileprogress`);
    buttonForm.classList.remove('filepondUpload');
    buttonForm.removeAttribute('disabled');
  },
});

// get a reference to the input element
const filepondInput = document.querySelector(
  '#filepondFileUploader input[type="file"]'
);

// create a FilePond instance at the input element location
const filepondObject = FilePond.create(filepondInput, {
  maxFiles: 5,
  acceptedFileTypes: ['image/*'],
  labelIdle:
    '<div class="image-upload__file-upload-content">Add images</div>',
  files: filepondInitialFiles,
  onprocessfiles() {
    console.log('onprocessfiles');
    buttonForm.classList.remove('filepondUpload');
    buttonForm.removeAttribute('disabled');
  },
});

Ответы [ 2 ]

1 голос
/ 07 августа 2020

Вам необходимо определить свойство server для компонента. Вы можете использовать v-bind:server="myServer", а затем добавить его к данным вашего компонента.

<file-pond
        name="test"
        ref="pond"
        v-bind:server="myServer"/>
export default {
    name: 'app',
    data: function() {
        return {
            myServer: {
                // server config here
            }
        };
    },
    components: {
        FilePond
    }
};

Если вам нужен setOptions, вы можете импортировать его из vueFilePond

import vueFilePond, { setOptions } from 'vueFilePond'
0 голосов
/ 07 августа 2020

Согласно @Rik, я внес следующие изменения:

Эти изменения были упомянуты им в LINK

            <file-pond
                name="test"
                ref="pond"
                label-idle="Drop files here..."
                :allow-multiple="true"
                accepted-file-types="image/jpeg, image/png"
                :files="myFiles"
                :server="serverconfig"
            />
    data:() => ({
        serverconfig: {
            process(fieldName, file, metadata, load, error, progress, abort) {

                // set data
                const formData = new FormData();
                formData.append('avatar', file, file.name);

                // related to aborting the request
                const CancelToken = this.$axios.CancelToken;
                const source = CancelToken.source();

                // the request itself
                this.$axios({
                    method: 'put',
                    url: 'user-info/',
                    data: formData,
                    cancelToken: source.token,
                    onUploadProgress: (e) => {
                        // updating progress indicator
                        progress(e.lengthComputable, e.loaded, e.total);
                    }
                }).then(response => {
                    // passing the file id to FilePond
                    load(response.data.data.id)
                }).catch((thrown) => {
                    if (this.$axios.isCancel(thrown)) {
                        console.log('Request canceled', thrown.message);
                    } else {
                        // handle error
                    }
                });

                // Setup abort interface
                return {
                    abort: () => {
                        source.cancel('Operation canceled by the user.');
                    }
                };
            }
        },

    })

Невозможно прочитать свойство ax ios. Что я делаю не так

...