Загрузка pdf файла в laravel vuejs Axios - PullRequest
0 голосов
/ 24 января 2020

Я создал проект для книжного магазина, и в разделе информации о сотрудниках я хочу загрузить файл PDF, используя приведенный ниже код. Это дает мне следующую ошибку. Я пробовал несколько дней, но не смог найти решение если есть какой-либо пример, пожалуйста, направьте меня, любая помощь будет высоко оценена требуется.

код контроллера

public function store(Request $request)
  {
       $DocumentType= new DocumentType();
                  $this->validate($request,[
            'name'=>'required',
            'file' => 'required',                
        ]);

        $DocumentType->name = $request->input('name');
        $fileName = time().'.'.$request->file->extension();  
        $request->file->move(public_path('Files'), $fileName);
        $DocumentType->file =  $name;
         $DocumentType->save();
         return response()->json($DocumentType);

  }

Vue код

<template>
  <div class="container">
 <div
      class="modal fade"
      id="addNew"
      tabindex="-1"
      role="dialog"
      aria-labelledby="addNewLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" v-show="!editMode" id="addNewLabel">ثبت اسناد جدید</h5>
            <h5 class="modal-title" v-show="editMode" id="addNewLabel">تمدید اسناد</h5>

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true" style="margin-right: 317px;">&times;</span>
            </button>
          </div>
          <form
            @submit.prevent="editMode ? updateDocumentType() : createDocumentType()"
            enctype="multipart/form-data"
          >
            <div class="modal-body">
              <div class="form-group">
                <input
                  v-model="form.name"
                  placeholder="نام"
                  type="text"
                  name="name"
                  class="form-control"
                  :class="{ 'is-invalid': form.errors.has('name') }"
                />
                <has-error :form="form" field="name"></has-error>
              </div>
              <div class="form-group">
                <label for="file" class="col-sm-4 control-label">File</label>

                <div class="col-sm-12">
                  <input
                    type="file"
                    class="form-input"
                    :class="{ 'is-invalid': form.errors.has('file') }"
                    id="file"
                    name="file"
                  />
                  <has-error :form="form" field="file"></has-error>
                </div>
              </div>

              <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">لغو</button>

                <button
                  v-show="editMode"
                  :disabled="form.busy"
                  type="submit"
                  class="btn btn-success"
                >تمدید</button>
                <button
                  v-show="!editMode"
                  :disabled="form.busy"
                  type="submit"
                  class="btn btn-primary"
                >ثبت</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
</template>
  </div>
<script>
  createDocumentType() {
      // axios.get("api/getAllDocumentTypeDocumentType").then(response => {
      //   let data = response.data;

      if (this.form.name == "") {
        toast.fire({
          type: "warning",
          icon: "warning",
          html: "<h5>نام لازم است.</h5>"
        });
      }
      // else if (this.form.file == "") {
      //   toast.fire({
      //     type: "warning",
      //     icon: "warning",
      //     html: "<h5>لطفا،اسناد را انتخاب نماید.</h5>"
      //   });
      // }
      else {
        this.form
          .post("api/DocumentType")
          .then(() => {
            //    the below function will be use to reload the page

            //   this.$emit("refreshPage");
            $("#addNew").modal("hide");
            toast.fire({
              icon: "success",
              type: "success",
              html: "<h5> اسنادموافقانه اجاد گردید</h5>"
            });
            Fire.$emit("refreshPage");
            this.form.reset();
            //   this.$Progress.finish();
          })
          .catch(er => {
            console.log(er);
          });
      }
    }
</script>

Код таблицы миграции

 public function up()
    {
        Schema::create('document_types', function (Blueprint $table) {
            $table->bigIncrements('id');
             $table->string('name');            
            $table->string('file')->nullable();
             $table->softDeletes();
            $table->timestamps();
        });
    }

Код в маршруте API

Route::apiResources(['DocumentType'=>'API\DocumentTypeController']);
Route::get('getAllDocumentType','API\DocumentTypeController@getAll');

1 Ответ

0 голосов
/ 24 января 2020

Указанные данные неверны. "," Errors ": {" file ": [" Поле файла обязательно для заполнения. Эта ошибка вызвана тем, что в вашей полезной нагрузке не существует файла после отправки вашей формы.

в вашей форме, привяжите данные к вашему входному файлу, как то, что вы сделали со своим входным именем. как это

<input
      type="file"
      v-model="form.file"
      class="form-input"
      :class="{ 'is-invalid': form.errors.has('file') }"
       id="file"
      name="file"
 />

Или, присоедините событие к этому входу файла и обработайте предоставленный файл. вот так

<input
          type="file"
          class="form-input"
          :class="{ 'is-invalid': form.errors.has('file') }"
          id="file"
          name="file"
          @change="selectFile"
/>

Затем в ваших методах создайте также функцию selectFile

methods: {
    selectFile(file) {
         if(file == "") return false

         this.form.file = file.target.files
         console.log(this.form.file)
    }
}
...