Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

laravel - Cannot save multiple Image using Form Data

First of all this is the error that I get.enter image description here

This is my first time working with Multiple Image with other Inputs.

as you can see in my FormData Headers the picture File is an Empty Array.

enter image description here

But inside the console it returns a file.

enter image description here

my question for this one that is this good? because the picture that I'm sending is a PNG one but it only says FILE.

This is my Vue Code.

 <q-dialog
  v-model="uploadForm"
  transition-show="slide-up"
  transition-hide="slide-down"
  persistent
>
  <q-card style="width: 700px; max-width: 50vw;">
    <q-card-section>
      <div class="text-h6">Add Product</div>
    </q-card-section>
    <div class="q-pa-md">
      <form
        action="http://127.0.0.1:8000/api/createProduct"
        class="q-gutter-md"
        method="POST"
        enctype="multipart/form-data"
      >
        <q-input outlined label="Product name" v-model="data.productName" />

        <q-input
          multiple="multiple"
          outlined
          type="file"
          accept="image/png,jpg/jpeg"
          @change="onFilePicked"
          ref="file"
        >
          <template v-slot:prepend>
            <q-icon name="attach_file" />
          </template>
        </q-input>
        <div>
          <div class="image-category">
            <div v-for="(image, key) in data.picture" :key="key">
              <div class="image-item">
                <img
                  class="grid"
                  :src="image.src"
                  width="300"
                  height="300"
                />
              </div>
            </div>
          </div>
        </div>

        <q-input outlined label="Description" v-model="data.description" />

        <q-input
          prefix="? "
          type="number"
          outlined
          label="Price"
          v-model="data.price"
        />

        <q-select
          square
          outlined
          v-model="data.category_id"
          :options="categories"
          :option-value="'id'"
          :option-label="'categoryName'"
          label="Category"
        />

        <div class="q-ma-md float-right">
          <q-btn label="Submit" color="primary" @click="createProduct" />
          <q-btn
            label="Cancel"
            color="primary"
            flat
            class="q-ml-sm"
            @click="closeCreateModal"
          />
        </div>
      </form>
    </div> </q-card
></q-dialog>

My returning Data()

  data: {
    picture: [],
    productName: "Grizzly Bear",
    description: "Machaba.",
    price: "260000",
    category_id: []
  },

my @Change in accepting multiple Images.

    onFilePicked(e) {
  let selectedFiles = e.target.files;
  for (let i = 0; i < selectedFiles.length; i++) {
    let img = {
      src: URL.createObjectURL(selectedFiles[i]),
      file: selectedFiles[i]
    };
    this.data.picture.push(img);
    console.log(this.data.picture, "inside");
  }
  console.log(this.data.picture, "outside");
},

My CreatingProduct method.

createProduct() {
  let t = this.data;

  if (
    t.picture == "" ||
    t.productName.trim() == "" ||
    t.description.trim() == "" ||
    t.price == "" ||
    t.categories == ""
  ) {
    this.uploadForm = false;

    this.$q
      .dialog({
        title: "Incomplete Details",
        message: "Please fill up all the fields in the Product",
        persistent: true,
        color: "negative"
      })
      .onOk(() => {
        this.uploadForm = true;
      });
  } else {
    let formData = new FormData();
    const picture = JSON.stringify(this.data.picture); // returns [object, object] so I needed to do 
 //this.
    const category_id = JSON.stringify(this.data.category_id); 

    formData.append("picture", picture);
    formData.append("productName", this.data.productName);
    formData.append("description", this.data.description);
    formData.append("price", this.data.price);
    formData.append("category_id", category_id);

    let config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };

    this.$axios
      .post("http://127.0.0.1:8000/api/createProduct", formData, config)
      .then(response => {
        this.products.unshift(response.data);
        this.uploadForm = false;
        (this.data = ""),
          this.$q.notify({
            icon: "info",
            message: "Product Added Successfully",
            color: "positive"
          });
      })
      .catch(() => {
        this.$q.notify({
          color: "negative",
          position: "top",
          message: "Unable to save Product",
          icon: "report_problem"
        });
      });
  }
}},

my Backend in laravel

    public function createProduct(Request $request)
{
    $this->validate($request,[
        'productName' => 'required',
        'description' => 'required',
        'picture' => 'required|image|mimes:jpg,png,jpeg|max:2048',
        'price' => 'required',
        'category_id' => 'required'
    ]);

    $product = new Product($request->input());


    if($request->hasFile('picture')){
        foreach($request->file('picture') as $file){
            $name = $file->getClientOriginalName();
            $file->move(public_path().'/uploads/',$name);
            $product->picture = $name;
        }
    }

    $product->save();

    return response()->json($product);

}

Can anyone explain to me what is wrong? I made my research and it doesn't work. and also how do you edit a multiple Image? How would you select a specific image in the Index to make that one being edit.

this is my first time working with Quasar + Laravel in creating a Product with Multiple Image.

question from:https://stackoverflow.com/questions/65840750/cannot-save-multiple-image-using-form-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you are doing some things wrong, if you use a framework try to use it as it was intended either the validations or components they have, I detail an example

new Vue({
    el: '#q-app',
    data: function() {
        return {
            uploadForm: true,
            data: {
                picture: [],
                productName: "Grizzly Bear",
                description: "Machaba.",
                price: "260000",
                category_id: null
            },
            categories: [
                { id: 1, categoryName: 'categoria 1' }
            ]
        }
    },
    methods: {
        createProduct() {
            this.$q.loading.show()
            let formData = new FormData()

            formData.append("picture", this.data.picture);
            formData.append("productName", this.data.productName);
            formData.append("description", this.data.description);
            formData.append("price", this.data.price);
            formData.append("category_id", this.data.category_id.id);

            axios.post('http://localhost:8000/', formData, {
                'headers': {
                    'Content-Type': 'multipart/form-data;'
                }
            }).then((response) => {
                alert(response)
            }).catch(error => {
                if (error) {
                    console.log('error', error)
                }
            }).finally(() => {
                this.$q.loading.hide()
            })
        },
        closeCreateModal() {
            alert('close')
        },
    }
})
<link rel="stylesheet"
      type="text/css"
      href="https://cdn.jsdelivr.net/npm/@quasar/extras/material-icons/material-icons.css">
<link rel="stylesheet"
      type="text/css"
      href="https://cdn.jsdelivr.net/npm/quasar/dist/quasar.min.css">
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/quasar/dist/quasar.umd.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="q-app">
  <q-dialog v-model="uploadForm"
            transition-show="slide-up"
            transition-hide="slide-down"
            persistent>
    <q-card style="width: 700px; max-width: 50vw;">
      <q-card-section>
        <div class="text-h6">Add Product</div>
      </q-card-section>
      <q-card-section class="q-pt-none">
        <div class="q-pa-md">
          <q-form @submit="createProduct"
                  class="q-gutter-md">
              <q-input outlined
                       label="Product name"
                       v-model="data.productName"
                       :rules="[val => !!val || 'Field is required']"></q-input>

              <q-file multiple outlined v-model="data.picture" label="Outlined" accept="image/png,jpg/jpeg"
:rules="[val => !!val || 'Field is required']">
                <template v-slot:prepend>
                <q-icon name="attach_file" ></q-icon>
                </template>
              </q-file>
              <q-input outlined
                       label="Description"
                       v-model="data.description"
                       :rules="[val => !!val || 'Field is required']"></q-input>
              <q-input prefix="? "
                       type="number"
                       outlined
                       label="Price"
                       v-model="data.price"
                       :rules="[val => !!val || 'Field is required']"></q-input>
              <q-select square
                        outlined
                        v-model="data.category_id"
                        :options="categories"
                        option-value="id"
                        option-label="categoryName"
                        label="Category"
                        :rules="[val => !!val || 'Field is required']"
                        ></q-select>
              <div>
                <q-btn label="Submit"
                       color="primary"
                       type="submit"></q-btn>
                <q-btn label="Cancel"
                       @click="closeCreateModal"
                       flat class="q-ml-sm"></q-btn>
            </div>
          </q-form>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...