pqina / vue-filepond

🔌 A handy FilePond adapter component for Vue
https://pqina.nl/filepond
MIT License
1.93k stars 128 forks source link

upload file to server #154

Closed falahatiali closed 4 years ago

falahatiali commented 4 years ago

How can I upload files in the server? I have set server property in the file-pond tag. as following:

 :server="/api/avatar/upload"

but when I want to get file on the server-side I have gotten the null value. or I have used as following

:server="server"

and in the script section:

        data: function() {
            return {
              form: new Form({
                    name: '',
                     email: ''
               }),
               myFiles: [],
                             progress:0,
                                server:{
                  process: function(fieldName, file, metadata, load, error, progress, abort){
                      const formData = new FormData();
                      formData.append('file', file, file.name);
                      axios({
                          method: 'POST',
                          url: '/api/user/avatar/upload',
                          data: formData,
                          onUploadProgress: (e) => {
                              progress(e.lengthComputable, e.loaded, e.total)
                          }
                      }).then(response => {
                          load(response.file)
                      }).catch((thrown) => {
                          if (axios.isCancel(thrown)) {
                              console.log('Request canceled', thrown.message)
                          } else {
                              // handle error
                          }
                      })
                  }
                                }
            };
        },

but I am not able to upload on the server. I think its documentation hasn't described these problems very well.

rikschennink commented 4 years ago

FilePond uploads both a json string and a file object, maybe that’s what’s wrong?

falahatiali commented 4 years ago

@rikschennink

but I don't receive any data in the backend. you can see the following code

falahatiali commented 4 years ago
<template>
    <card >
        <form @submit.prevent="update" @keydown="form.onKeydown($event)" enctype="multipart/form-data">
            <alert-success :form="form" :message="$t('info_updated')" />

            <!-- Name -->
            <div class="card border-primary" >
                <div class="card-header">
                    <ul class="nav nav-pills card-header-pills">
                        <li class="nav-item">
                            <span class="nav-link">{{ $t('basic_info') }}</span>
                        </li>

                        <li class="nav-item">
                            <a class="nav-link disabled" href="#" tabindex="-1" >{{ $t('edit')}}</a>
                        </li>
                    </ul>
                </div>

                <div class="card-body">
                    <div class="row no-gutters">
                        <div class="col-md-4">
                            <file-pond
                                    name="file"
                                    ref="pond"
                                    label-idle="Click here of drag your file..."
                                    v-bind:allow-multiple="false"
                                    imageCropAspectRatio="1:1"
                                    imageResizeTargetWidth="200"
                                    allowImagePreview="true"
                                    imagePreviewMinHeight="60"
                                    imagePreviewMaxHeight="200"
                                    imagePreviewHeight="80"
                                    imagePreviewMaxFileSize="100m"
                                    allowImageCrop="true"
                                    allowImageEdit="true"
                                    imageEditInstantEdit="false"
                                    imageEditAllowEdit="true"
                                    imageResizeTargetHeight="500"
                                    allowImageExifOrientation="true"
                                    stylePanelLayout="compact circle"
                                    styleLoadIndicatorPosition="center bottom"
                                    labelFileLoading="file is sending to server ..."
                                    labelFileProcessing="file is sending to server ..."
                                    styleButtonRemoveItemPosition="center bottom"
                                    styleImageEditButtonEditItemPosition="bottom center"
                                    accepted-file-types="image/jpeg, image/png"
                                    :server="server"
                                    v-bind:files="myFiles"
                                    v-on:init="handleFilePondInit"
                                    v-on:addfilestart="handleOnaddfilestart"
                                    v-on:addfile="handleOnaddfile"
                                    v-on:processfileprogress="handleOnprocessfileprogress"
                                    v-on:addfileprogress="handleOnaddfileprogress"
                                    v-on:processfilestart="handleOnprocessfilestart"
                                    v-on:error="handleOnerror"
                                    v-on:processfileabort="handleOnprocessfileabort"
                                    v-on:processfilerevert="handleOnprocessfilerevert"
                                    v-on:processfile="handleOnprocessfile"
                                    v-on:updatefiles="handleOnupdatefiles"
                            />
                            <div class="progress">
                                <div class="progress-bar" role="progressbar"
                                         v-bind:style="{ width: progress + '%'}" v-bind:aria-valuenow="progress"
                                         aria-valuemin="0" aria-valuemax="100">{{progress}} % </div>
                            </div>

                        </div>
                    </div>
                </div>
            </div>

            <br>
            <br>

        </form>
    </card>
</template>

<script>
    import Form from 'vform'
    import { mapGetters } from 'vuex'
    import Swal from 'sweetalert2';
    import i18n from '~/plugins/i18n'
    import axios from 'axios';

    import vueFilePond from 'vue-filepond';
    import 'filepond/dist/filepond.min.css';
    import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css';
    import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview';

    import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type';
    import FilePondPluginImagePreview from 'filepond-plugin-image-preview';
    import FilePondPluginImageExifOrientation from 'filepond-plugin-image-exif-orientation';
    import FilePondPluginImageCrop from 'filepond-plugin-image-crop';
    import FilePondPluginImageResize from 'filepond-plugin-image-resize';
    import FilePondPluginImageTransform from 'filepond-plugin-image-transform';
    import FilePondPluginImageEdit from 'filepond-plugin-image-edit';

    const FilePond = vueFilePond(FilePondPluginFileValidateType, FilePondPluginImagePreview  ,
        FilePondPluginImageExifOrientation,FilePondPluginImageCrop,
        FilePondPluginImageResize, FilePondPluginImageTransform,FilePondPluginImageEdit);

    export default {
        scrollToTop: false,

        metaInfo () {
            return { title: this.$t('app_name') }
        },
        data: function() {
            return {
                form: new Form({
                    name: '',
                    email: ''
                }),
                myFiles: [],
                progress:0,
                server:{
                    process: function(fieldName, file, metadata, load, error, progress, abort){
                        console.log('starting');
                        const formData = new FormData();
                        formData.append(fieldName, file, file.name);

                        const request = new XMLHttpRequest();
                        request.open('POST', '/api/user/avatar/upload');
                        request.upload.onprogress = (e) => {
                            console.log(e.lengthComputable, e.loaded, e.total);
                            progress(e.lengthComputable, e.loaded, e.total);
                        };

                        axios({
                            method: 'POST',
                            url: '/api/user/avatar/upload',
                            data: formData,
                            onprocessfileprogress: (e) => {
                                progress(e.lengthComputable, e.loaded, e.total)
                            }
                        }).then(response => {
                            console.log(response);
                            load(response.file)
                        }).catch((thrown) => {
                            if (axios.isCancel(thrown)) {
                                console.log('Request canceled', thrown.message)
                            } else {
                                // handle error
                            }
                        })
                    },
                    load(uniqueField , load ,error){
                        console.log('saalammmm');
                    }
                }
            };
        },
        methods: {
            handleFilePondInit: function() {
                //console.log('FilePond has initialized');
                this.$refs.pond.getFiles();
            },
            handleOnaddfilestart: function(file){},
            handleOnaddfile: function(error , file){},
            handleOnprocessfileprogress: function(file, progress){
                this.progress = Math.round(progress * 100);
            },
            handleOnaddfileprogress: function(file, progress){},
            handleOnprocessfilestart: function(){},
            handleOnerror: function(){},
            handleOnprocessfileabort: function(){},
            handleOnprocessfilerevert: function(){},
            handleOnprocessfile: function(error, file){
                Swal.fire({
                    type: 'success',
                    title: i18n.t('success_alert_title'),
                    text: i18n.t('avatar_successfully_uploaded'),
                    reverseButtons: true,
                    confirmButtonText: i18n.t('ok'),
                    cancelButtonText: i18n.t('cancel')
                });
                console.log(file);
            },
            handleOnupdatefiles: function f() {}
        },

        computed: mapGetters({
            user: 'auth/user'
        }),

        created (){ },
        components: {
            FilePond
        }
    }
</script>
rikschennink commented 4 years ago

Does it log “starting” to console?

Do you see the upload request in your dev tools network console?

If so, do you see the payload in the request or not?

If you see it, the server isn’t handling the file and it’s a server issue. If you don’t see the request but see “starting” it’s a problem with your axios implementation in the process function. If you don’t see starting, it’s a FilePond config issue.

falahatiali commented 4 years ago

I see starting but I have so ambiguous. first can I set server property alone without binding? I mean in the <file-pond ... /> tag I set server="/api/user/avatar/upload" ? what is the difference between them?

should I implement process, load, and ....?

second: what is the role of other methods such as v-on:addfile="handleOnaddfile" ? should we implement them?

rikschennink commented 4 years ago

This part is not needed as it seems your posting with axios.

const request = new XMLHttpRequest();
                        request.open('POST', '/api/user/avatar/upload');
                        request.upload.onprogress = (e) => {
                            console.log(e.lengthComputable, e.loaded, e.total);
                            progress(e.lengthComputable, e.loaded, e.total);
                        };

Next step:

Do you see the upload request in your dev tools network console?

Droog159 commented 4 years ago

It working,delete it , i get reponse

rikschennink commented 4 years ago

closed because inactive