Как использовать Filepond в vue js и загружать файлы с помощью axios? - PullRequest
0 голосов
/ 07 сентября 2018

Мне нужно использовать axios для отправки пост-запроса с целью загрузки файлов с помощью Filepond Uploader.

Как я могу это сделать?

Я использую пользовательский обработчик процессов, как показано ниже, но он не работает.

processHandler: (fieldName, file, metadata, load, error, progress, abort) => {
        let formData = new FormData();
        let uploadPercentage = 0;
        formData.append('file', file);
        console.log(formData);

        HTTP.post('v1/upload', formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: function (progressEvent) {
              uploadPercentage = parseInt(Math.round((progressEvent.loaded * 100) / progressEvent.total));
              console.log(uploadPercentage);
            }.bind(this)
          })
          .then((response) => {
            console.log(response);
            // Should call the load method when done and pass the returned server file id
            // the load method accepts either a string (id) or an object
            // the unique server file id is used by revert and restore functions
            load(response.data.data.id);
          })
          .catch((error) => {
            console.error(error);
            error("Has error");
          });

        // Should call the progress method to update the progress to 100% before calling load
        // Setting computable to false switches the loading indicator to infinite mode
        // (computable, processedSize, totalSize)
        progress(true, 0, 1024);

        // Should expose an abort method so the request can be cancelled
        return {
          abort: () => {
            // User tapped abort, cancel our ongoing actions here

            // Let FilePond know the request has been cancelled
            abort();
          }
        };
      }

Я использую это руководство , но мне не совсем понятно, как я могу создать процесс выгрузки и загрузки для обработки ответа и запроса моего сервера.

Спасибо.

1 Ответ

0 голосов
/ 01 октября 2018

Автор FilePond здесь.

Я не совсем уверен, что понимаю описание проблемы, но постараюсь помочь. Я быстро взглянул на документы Axios (https://github.com/axios/axios) и настроил следующий фрагмент.

{
    processHandler: (fieldName, file, metadata, load, error, progress, abort) => {

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

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

        // the request itself
        axios({
            method: 'post',
            url: 'v1/upload',
            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 (axios.isCancel(thrown)) {
                console.log('Request canceled', thrown.message);
            } else {
                // handle error
            }
        });

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