0

Here I have written a code for multi upload images. And the functionality i dont know where I am going wrong. like while i am uploading an image. So in console terminal I am seeing only image name not image. So please tell me where I am going wrong I want to save the image in backend but I am getting only image name in vue code. So please tell me where I am going wrong. Please help me

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="app">
  <h2>Multiple Files</h2>
  <hr/>
  <label>
    <span>Files</span>
    <input type="file" multiple @change="handleFileUploads($event)" />
    <ul v-if="files.length">
      <li v-for="(name, i) in filesNames" :key="i">{{ name }}</li>
    </ul>
  </label>
  <div>
    <img v-for="image in images" :src="image" />
  </div>
  <br />
  <button @click="submitFiles()">Submit</button>
</div>

vue.js

Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data() {
    return {
      files: [],
      images: [],
    }
  },
  computed: {
    filesNames() {
      const fn = []
      for (let i = 0; i < this.files.length; ++i) {
        fn.push(this.files.item(i).name)
      }
      return fn
    }
  },
  methods: {
    handleFileUploads(event) {
      this.files = event.target.files;
      this.images = [...this.files].map(URL.createObjectURL);
    },
// how to access img_fna or sal to backend in from this snippet of code.
      submitForm: function(){
                  const img_fna = []
                  for (let i = 0; i < this.files.length; ++i) {
                  let file = this.files[i];
                    img_fna.push(file)
                  }
                    var reader;
                    var file;
                    var i;
                    const sal = []

                    for (i = 0; i < files_s.length; i++) {
                        file = files_s[i];
                        reader = new FileReader();
                        reader.onload = (function(file) {
                          return function(e) {
                            sal.push(e.target.result);

                          };
                        })(file);
                        reader.readAsDataURL(file);
                      }
            axios({
                method : "POST",
                url: "{% url 'service-ad' %}", //django path name
                headers: {'X-CSRFTOKEN': '{{ csrf_token }}',
                'Content-Type': 'application/json'},
                data : {
                "images": sal,
                "image_url": img_fna,
                },//data
              }).then(response => {
                  this.success_msg = response.data['msg'];
              }).catch(err => {
                     this.err_msg = err.response.data['err'];
      
              });
          }
  }
})
Inayat Kazi
  • 113
  • 1
  • 9
  • Does this answer your question? [HTML input type=file, get the image before submitting the form](https://stackoverflow.com/questions/5802580/html-input-type-file-get-the-image-before-submitting-the-form) – idkwhatsgoingon Nov 30 '21 at 10:00
  • i dont want to preview the image i want to access the image that i can pass in backend. – Inayat Kazi Nov 30 '21 at 10:30
  • So here I am getting only image name – Inayat Kazi Nov 30 '21 at 10:30
  • 1
    What happens with the formData once you post it to your backend? What backend are you using. Does it support images. You are missing a lot of information making it nearly impossible to help you. Please start by changing the catch callback to `.catch(function(error) { console.log(error) });` and then provide some info on your backend setup – idkwhatsgoingon Nov 30 '21 at 10:44
  • If you want to access the image, you will have to get the File object inside the `change` event of the INPUT field - and then instantiate a FileReader and use its `readAsDataURL()` method. Then you will have the image as Bas64-encoded data URI. You can draw it onto Canvas or use it as SRC in IMG tag. – IVO GELOV Nov 30 '21 at 11:07

1 Answers1

0

If I understand you correctly, you want to post your images list to backend, but you don't know how to get data from files like this: enter image description here and send data to backend. And in backend, you can only see image name, am i right?

If so, here is my example code:

    async submitFile() {
      let filelist = [];
      for (let i = 0; i < this.files.length; ++i) {
        filelist.push(
          await (async (cur) => {
            return new Promise((resolve, reject) => {
              const fr = new FileReader();
              fr.onload = () => {
                resolve(fr.result);
              };
              fr.readAsDataURL(cur);
            });
          })(this.files.item(i))
        );
      }
      let formData = new FormData();
      formData.append("files", filelist);
      axios.post('/multiple-files', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(function() {
          console.log('SUCCESS!!');
        })
        .catch(function() {
          console.log('FAILURE!!');
        });
    },

The focus is to use FileReader.readAsDataURL to get the image as base64 encoded data. Then you have image data in the backend like this: enter image description here