簡體   English   中英

如何使用 vue 組件和 Laravel 控制器上傳文件 [Axios]

[英]How to upload file with vue component and laravel controller [Axios]

我想將帶有 vue 組件的圖像文件上傳到 Laravel 控制器。 當我單擊提交按鈕名稱/描述/地址已保存但圖像名稱未保存時,我的問題發生

我想將圖像名稱保存到我的數據庫中,但 if($request->hasFile('id_image')) 總是返回 false

你能告訴我解決這個解決方案的語法嗎?

這是 create.vue

       <form action="/listorgs" enctype="multipart/form-data">
          <div class="form-group">
            <label>name_org:</label>
            <input type="text" class="form-control" v-model="org.name_org">
          </div>
          <div class="form-group">
            <label>picture:</label>
            <input
              type="file"
              @change="onFileChange"
              name="name_image"
              id="id_image"
              class="inputFile"
            >
          </div>
          <div class="form-group">
            <label>description:</label>
            <textarea
              class="form-control mb-2"
              rows="5"
              v-model="org.description"
            ></textarea>
          </div>
          <div class="form-group">
            <label>address:</label>
            <input type="text" class="form-control" v-model="org.address">
          </div>
          <div class="form-group">
            <button class="btn btn-primary" v-on:click="addNewOrg()">Save</button>
          </div>
        </form>

在出口默認

data() {
    return {
      org: {
        name_org: "",
        description: "",
        address: "",
        image: ""
      }
    };
  },
  methods: {
    addNewOrg() {
      axios
        .post("/api/listorgs", this.org)
        .then(response => {
          console.log(response.data);
          if (response.data.etat) {
            this.org = {
              name_org: response.data.etat.name_org,
              description: response.data.etat.description,
              address: response.data.etat.address,
              picture: response.data.etat.image
            };
          }
        })
        .catch(error => {
          console.log("errors: ", error);
        });
        console.log(this.image);
    },
    onFileChange(e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.createImage(files[0]);
    },
    createImage(file) {
      let reader = new FileReader();
      reader.onload = e => {
        this.org.image = e.target.result;
      };
      reader.readAsDataURL(file);
    }
  }

這是我的控制器

$listorg=new ListOrg();
$listorg->name_org=$request->get('name_org');
$listorg->description=$request->get('description');
$listorg->address=$request->get('address');
if($request->hasFile('name_image')){
    $listorg->picture= $request->image->store('images');
}
$listorg->save();
return response()->json($listorg);

它說在此處輸入圖片說明

您的JavaScript引用了“圖片”字段,而您的字段名為“ id_image”?

抱歉,我無法發表評論(評分),但也許嘗試堅持某種約定?

嘗試僅在控制器方法中轉儲並處理整個請求。

可能會給您很好的提示,以解決問題。

您會混淆FORM POST的3種不同方法。 讓我澄清一下:

  1. 如果你想用愛可信,改變你的形式和刪除actionenctype ,以防止混淆,你正在做一個AJAX POST,而不是一個常規的表單POST。

  2. 確定您要嘗試以base64編碼還是二進制形式檢索文件。 看起來您想執行二進制操作,因此擺脫了base64冗余代碼。 並直接將文件輸入與v模型綁定。

  3. 好的,現在我們知道您要執行二進制操作,因為您的服務器端代碼具有$request->hasFile('name_image') ,您需要將其提交為FormData對象。

因此,您的代碼如下所示:

<!-- point #1, we made it clear that it is an AJAX submit 
by handling the submit event. -->
     <form @submit.prevent="addNewOrg">
          <div class="form-group">
            <label>name_org:</label>
            <input type="text" class="form-control" v-model="org.name_org">
          </div>
          <div class="form-group">
            <label>picture:</label>
<!-- remove change event handling and bind 
the file directly to the image property -->
            <input
              type="file"
              v-model="org.image"
              class="inputFile"
            >
          </div>
          <div class="form-group">
            <label>description:</label>
            <textarea
              class="form-control mb-2"
              rows="5"
              v-model="org.description"
            ></textarea>
          </div>
          <div class="form-group">
            <label>address:</label>
            <input type="text" class="form-control" v-model="org.address">
          </div>
          <div class="form-group">
<!-- point #1, change the button type to submit button.  
The form and submit button combination also has a 
side-affect/benefit of auto-submit if user hit 
the enter button on the form. -->
            <button class="btn btn-primary" type="submit">Save</button>
          </div>
        </form>
data() {
    return {
      org: {
        name_org: "",
        description: "",
        address: "",
        image: null
      }
    };
  },
  methods: {
    addNewOrg() {
      // point #2, to do binary data upload 
      // you need to use FormData
      var fd = new FormData();
      for (var key in this.org) {
        fd.append(key, this.org[key]);
      }

      axios
        .post("/api/listorgs", fd)
        .then(response => {
          console.log(response.data);
          if (response.data.etat) {
            this.org = {
              name_org: response.data.etat.name_org,
              description: response.data.etat.description,
              address: response.data.etat.address,
              picture: response.data.etat.image
            };
          }
        })
        .catch(error => {
          console.log("errors: ", error);
        });
        console.log(this.image);
    }

/* Since you're doing binary submit, you don't need 
all that base64 image data url codes, unless you 
want to do something else like preview image 
canvas before upload or something 
similar. */

然后是服務器端代碼:

$listorg=new ListOrg();
$listorg->name_org=$request->get('name_org');
$listorg->description=$request->get('description');
$listorg->address=$request->get('address');

/* you're submitting it as image with ajax
 not a regular form post so you don't want 
to use the name of the input.  That's why 
I removed the input name in the html 
above to avoid confusion */

if($request->hasFile('image')){
    $listorg->picture= $request->image->store('images');
}
$listorg->save();
return response()->json($listorg);

$ listorg->圖片。

如果我是對的,則從控制器返回的數據不具有image屬性。 嘗試console.log(this.picture);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM