0

so im coding with vue and im using cloudconvert api which converts my files to pdf and gets me the number of pages, also im using a package called dropzone which i can drop files into it and it handles them and sends them it also does other restrictions that helps alot the thing is when i click "upload document" the dropzone sends the files before i create a job at cloud convert by sending post request because when i create a job it will give me the params that i need to send with the file and the upload link which both will be used by dropzone to send its request now dropzone has a parameter called "sending" which you can pass to it a function called "onsending" that has the FormData of the file before sending it, inside the onsending i call a function that creates the job

i can make it work by sending 1 file and i can do that by putting the handleimage() function in uploaddocument function but when i want to send multiple files i thought that if i put handleimage() inside onsending it would work but it didnt what happened is it sends the files before handleimage() gets the Parameters FormData

purpose and role of each function handleimage: creates the job in cloudconvert uploaddocument: initiate the upload process onsending: runs each time before sending the files or before sending the request

This is the code :

<template>
        <p>job ID: {{ jobID }}</p>

<br>
<p>Parameters: {{ pramnamed }}</p>
  <div class="content-wrapper">
    <div class="dropzone-icon">
      <img src="@/assets/dropzone_icon.svg" alt="Dropzone Icon" />
    </div>

    <DropZone
      :dropzoneClassName="customDropzoneClass"
      :dropzoneMessageClassName="customDropzoneMessageClass"
      :dropzoneItemClassName="customDropzoneItemClass"
      :dropzoneDetailsClassName="customDropzoneDetailsClass"
      :maxFiles="Number(10)"
      
      ref="dropzoneRef"
      :uploadOnDrop="false"
          :url= this.urld
      :headers="{'Authorization' : 'Bearer '}"
      @sending="onSending"
      
      :acceptedFiles="[
        'pdf',
        'eps',
        'jpg',
        'tiff',
        'png',
        'JPEG',
        'svg',
        'pages',
        'doc',
        'docx',
        'ppt',
        'pptx',
        'xls',
        'xlsx',
        'txt',
      ]"
    />
   
  </div>
 
<button @click="UploadDocument">upload document</button>

  <p class="middle-align">Paste <a href="" @click.prevent="openImageURLInput">URL</a> image link</p>
  <div v-if="showModal" class="modal" @click="closeModal">
    <div class="modal-content" @click.stop>
      <span class="close-button" @click="closeModal">&times;</span>
      <input type="text" v-model="imageUrl" placeholder="Enter image URL" />
      <button @click="handleImageUrl">Submit</button>
    </div>
  </div>

 
<div class= boxingg>
  <h2 class="faq-title">Leave the printing<br>
to us!</h2>
<p class="paragraphh" >Simply upload your documents and insert coins and your documents will be printed immediately </p>
<div class="containerr">
    <div class="image-container">
      <img src="@/assets/recycle pic.svg" class="imagee" />
    </div>
  </div>
  <h2 class="faq-title">What is Bunt?<br>
to us!</h2>
<p class="paragraphh" >Is commercial vending machine that prints paper on demand, we have built it to<br> be as easy as taking a picture by having vending machine accept as many types of files as possible.</p>
  <div class="faq-container">
    <h2 class="faq-title">Frequently Asked Questions</h2>
  <div v-for="(faq, index) in faqs" :key="index" class="faq-item">
    <div class="faq-question" @click="toggleFaqAnswer(index)">
      <span>{{ faq.question }}</span>
      <span class="faq-arrow" :class="{ 'flipped': activeFaqIndex === index }">
        <img src="@/assets/cheveron-down.svg" alt="Chevron Down" />
      </span>
    </div>
    <div v-if="activeFaqIndex === index" class="faq-answer">
      <p>{{ faq.answer }}</p>
    </div>
  </div>
</div>
</div>


</template>

<script>
import axios from "axios";
import { defineComponent, ref } from "vue";
import { DropZone } from "dropzone-vue";
//local data storage
import { useFilesStore } from '@/stores/files';
//api logic
// import {taskss} from "@/API/cloudconvert";
//css code
import '@/assets/styles/homepage.css';

export default defineComponent({
  data() {
    return {
     
      jobID: "",
      urld: "https://eu-central.storage.cloudconvert.com/tasks",
      pramnamed: { },
                         
    }
  },

  components: {
    DropZone,
  },
  name: "HomePageContent",










 
  methods: {
     onSending(file, xhr, formData) {
    // Ensure handleImage runs before modifying formData
   this.handleImage();

    console.log("pramnamed in onSending:", this.pramnamed); // Debugging line

    // Ensure pramnamed is properly defined
    if (this.pramnamed) {
      Object.entries(this.pramnamed).forEach(([key, value]) => {
        formData.append(key, value);
      });
    } else {
      console.error('pramnamed is undefined or null');
    }
}},









  setup() {
    const dropzoneRef = ref(null);
    const customDropzoneClass = "my-custom-dropzone";
    const customDropzoneMessageClass = "my-custom-dropzone-message";
    const customDropzoneItemClass = "my-custom-dropzone-item";
    const customDropzoneDetailsClass = "my-custom-dropzone-details";
    const showModal = ref(false);
    const imageUrl = ref("");
    const activeFaqIndex = ref(-1);
    const filesStore = useFilesStore();
    const faqs = [
      {
        question: "What is the price to print 1 paper?",
        answer: "The price to print 1 paper is $0.10.",
      },
      {
        question: "What file types does the machine accept?",
        answer: "The machine accepts    pdf, eps, jpg, tiff, png, JPEG, svg, pages, doc, docx, ppt, pptx, xls, xlsx, txt file types.",
      },
      {
        question: "How long does it take before order code expires?",
        answer: "The order code expires in 3 days.",
      },
      {
        question: "How many files can I upload?",
        answer: "You can upload up to 10 files at a time.",
      },
    ];

    function openImageURLInput() {
      showModal.value = true;
    }
    function closeModal() {
      showModal.value = false;
      imageUrl.value = "";
    }
    function toggleFaqAnswer(index) {
      if (activeFaqIndex.value === index) {
        activeFaqIndex.value = -1;
      } else {
        activeFaqIndex.value = index;
      }
    }


   



async function UploadDocument(){
  
       await dropzoneRef.value.processQueue();
      const tasks = await waitForJobCompletion(this.jobID);
      console.log("Completed Tasks:", tasks);
      const metadataTask = tasks.find((task) => task.name === "task-2");
      if (!metadataTask) {
        throw new Error("Metadata task not found");
      }
      filesStore.addFile({
        id: this.jobID,
        name: fileMetadata.FileName,
        pageCount: fileMetadata.PageCount,
        size: fileMetadata.FileSize,
      });
    }





    const message = ref("");
    async function waitForJobCompletion(jobId) {
      while (true) {
        const jobResponse = await axios.get(
          `https://api.cloudconvert.com/v2/jobs/${jobId}`,
          {
            headers: {
              Authorization:
                "Bearer ",
            },
          }
        );

        console.log("Job Response:", jobResponse.data);

        const jobStatus = jobResponse.data.data.status;
        const tasks = jobResponse.data.data.tasks;



        if (jobStatus === "finished") {
          return tasks;
        } else if (jobStatus === "error") {
          throw new Error("Job failed");
        }

        await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait for 5 seconds before polling again
      }
    }



    async function handleImage() {
      
      try {
        // Step 1: Create a job
        const jobResponse = await axios.post(
          "https://api.cloudconvert.com/v2/jobs",
          {
            tasks: {
              "import-1": {
                operation: "import/upload",
              },
              "task-1": {
                operation: "convert",
                input: ["import-1"],
                output_format: "pdf",
              }, 
              "task-2": {
                operation: "metadata",
                input: ["task-1"],
              },
              "export-1": {
                operation: "export/url",
                input: ["task-1"],
                inline: false,
                archive_multiple_files: false,
              },
            },
            tag: "jobbuilder",
          },
          {
            headers: {
              Authorization:
                "Bearer ",
            },
          }
        );
        // Access reactive data properties using this
        this.jobID = jobResponse.data.data.id;
       const importTask = jobResponse.data.data.tasks.find((task) => task.name === "import-1");
    if (importTask) {
      this.urld = importTask.result.form.url;
      this.pramnamed = importTask.result.form.parameters;
 
    } else {
      throw new Error("Import task not found");
    }


     
    this.message = `Uploaded document successfully with ID: ${jobId}`;
  } catch (error) {
        this.message = `Error uploading document: ${error.response ? error.response.data.message : error.message
          }`;
      }
}





    return {
      customDropzoneClass,
      customDropzoneMessageClass,
      customDropzoneItemClass,
      customDropzoneDetailsClass,
     
      openImageURLInput,
      showModal,
      imageUrl,
      closeModal,
    
      
      faqs,
      activeFaqIndex,
      toggleFaqAnswer,

      dropzoneRef,

//API
waitForJobCompletion,
handleImage,
UploadDocument,
message,



    };
  },
});
</script>

enter image description here

i want to be able to send multiple files but so far i was able to send 1 file only

0

0

Browse other questions tagged or ask your own question.