cretueusebiu / vform

Handle Laravel-Vue forms and validation with ease.
https://vform.vercel.app
MIT License
607 stars 120 forks source link

image upload #107

Closed iamjiten closed 3 years ago

iamjiten commented 4 years ago

thank you for great work.

i would like to ask, how should i post single file and multiple file.

robjuz commented 4 years ago

@jiten143 This is my solution.

I extended the vform and added some file upload features. You use it as normal. Additionally you can read the upload progress

import BaseForm from 'vform';
import {serialize} from "object-to-formdata";

class Form extends BaseForm {

    constructor(data = {}) {
        super(data);

        this.progress = null;
    }

    startProcessing() {
        super.startProcessing();
        this.progress = 0;
    }

    finishProcessing() {
        super.finishProcessing();
        this.progress = null;
    }

    clear() {
        super.clear();
        this.progress = null;
    }

    async submit(method, url, config = {}) {

        let newConfig = Object.assign(config, {
            transformRequest: [function (data, headers) {
                return serialize(data)
            }],

            onUploadProgress: e => {
                this.progress = Math.round( (e.loaded * 100) / e.total )
            }
        })

        return await super.submit(method, url, newConfig);
    }
}

Form.ignore.push('progress');

export default Form;

Example component

<template>
  <b-form @submit.prevent="handleSubmit">
    <b-form-group
        label="'File"
        label-for="file"
    >
      <b-form-file
          id="file"
          v-model="uploadForm.file"
          :state="uploadForm.errors.has('file') ? false : null"
      />
    </b-form-group>

    <b-progress
        v-show="uploadForm.busy"
        :value="uploadForm.progress"
        :max="100"
        show-progress
        animated
        class="mb-3"
    />

    <b-button
        :disabled="uploadForm.busy"
        variant="primary"
        type="submit"
    >
     Submit

      <b-spinner small v-if="uploadForm.busy"/>
    </b-button>
  </b-form>
</template>
<script>
import UploadForm from "@/plugins/uploadForm";

export default {
  name: 'FileUploadForm',
  props: {
    url: {
      type: String,
      required: true
    },
  },
  data() {
    return {
      uploadForm: new UploadForm({
        file: null
      }),
    }
  },
  methods: {
    handleSubmit() {
      this.uploadForm.post(this.url).then(() => {
        this.uploadForm.reset();
      })
    }
  }
}
</script>
stevebauman commented 4 years ago

Hey @robjuz, your implementation has saved me a ton of time, thanks so much for posting it!! ❤️

cretueusebiu commented 3 years ago

Added this by default now.