无法使用Vue.js将文件上传到Lumen后端?

时间:2019-08-08 07:37:01

标签: laravel file vue.js

我尝试使用vue.js作为前端技术并在后端使用laravel上传文件。我尝试使用formData javascript对象传递文件对象,但服务器响应,因为未传递值。 我试图使用console.log记录该文件,它会适当显示数据。 考虑到我已经丢弃了一些字段名称。

模板代码

<template>
  <b-container>
    <div align="center">
      <b-card class="mt-4 mb-4 col-md-8" align="left" style="padding: 0 0;">
        <card-header slot="header" />
        <b-form>
          <div class="row">
            <div class="col-6 col-md-6">
              <b-button
                type="submit"
                variant="success"
                class="float-right col-md-5"
                v-if="!update"
                @click="save"
                squared
              >
                <i class="fas fa-save"></i>
                Save
              </b-button>
            </div>
          </div>
          <hr style="margin-top: 10px;" />

          <b-form-group
            label-cols="12"
            label-cols-lg="3"
            label-for="input-2"
            label="Remark: "
            label-align-sm="right"
            label-align="left"
          >
            <b-form-textarea
              id="textarea"
              v-model="record.remark"
              rows="2"
              max-rows="3"
            ></b-form-textarea>
          </b-form-group>
          <b-form-group
            label-cols="12"
            label-cols-lg="3"
            label-for="input-2"
            label="Remark: "
            label-align-sm="right"
            label-align="left"
          >
            <b-form-file
              v-model="record.attachement"
              :state="Boolean(record.attachement)"
              placeholder="Choose a file..."
              drop-placeholder="Drop file here..."
            ></b-form-file>
          </b-form-group>
        </b-form>
        <status-message ref="alert" />
      </b-card>
    </div>
  </b-container>
</template>

Script Code

<script>
import { mapGetters, mapActions } from "vuex";

export default {
  props: ["id", "user_id"],
  data: () => ({
    record: {
      remark: "",
      attachement: null
    }
  }),

  methods: {
    ...mapActions([
      "addBenefitRequest",
    ]),
    save(evt) {
      evt.preventDefault();
      this.$validator.validate().then(valid => {
        if (valid) {
          const Attachement = new FormData();
          Attachement.append("file", this.record.attachement);
          var object = {
            remark: this.remark
          };
          this.addBenefitRequest(object, Attachement);              
        }
      });
    },
  },

  computed: mapGetters([
    "getStatusMessage",
    "getBenefitRequest",
  ])
};
</script>


    Store Code

    async addBenefitRequest({ commit }, object, Attachement) {
    try {
      const response = await axios.post(
        commonAPI.BENEFIT_BASE_URL + "/benefit-requests",
        object,
        Attachement,
        {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        }
      );
      commit("pushBenefitRequest", response.data);
      commit("setStatusMessage", "Record has been added.");
    } catch (error) {
      return error
  },

控制器代码

 public function store(Request $request, Request $request2)
    {
        $this->validate($request, [
           'employee_id' => 'required|string',        
           'requested_date' => 'required|date',                     
        //    'benefit_type_id' => 'required|string|exists:benefit_types,id',                     
           'reason' => 'required|string', 

        ]);  
        $this->validate($request2, [
            'attachement' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'

        ]); 
        // $success = BenefitRequest::exists($request->employee_id);    
        // if(!$success)
        //     return response()->json("Employee doesn't exist", 422);   
        $id = (string) Str::uuid(); 
        if($request2->attachement) 
        {
            $attachement = $request2->file('attachement')->store('Benefits');  
            $request->merge(['attachement' => $attachement]); 
        }    
        // $request->attachement = $request->file('attachement')->store('Benefits');  
        $request->merge(['id' => $id]); 
        BenefitRequest::create($request->all());

        return response()->json('Saved', 201);

    }

路线

$router->post('', 
         ['uses' => 'BenefitRequestController@store',
          'group'=>'Benefit requests',
        'parameter'=>'employee_id, requested_date, requested_by,  benefit_type_id, reason, remark, status',
        'response'=>'<statusCode, statusMessage>'
]);

1 个答案:

答案 0 :(得分:0)

这里是一个例子。你可以尝试

index.vue

`<div id="app">
  <div v-if="!image">
    <h2>Select an image</h2>
    <input type="file" @change="onFileChange">
  </div>
  <div v-else>
    <img :src="image" />
    <button @click="removeImage">Remove image</button>
  </div>
</div>`

    new Vue({
       el: '#app',
       data: {
          image: ''
        },
       methods: {
          onFileChange(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length)
            return;
            this.createImage(files[0]);
          },
          createImage(file) {
            var image = new Image();
            var reader = new FileReader();
            var vm = this;

            reader.onload = (e) => {
               vm.image = e.target.result;
            };
            reader.readAsDataURL(file);
          },
          removeImage: function (e) {
             this.image = '';
          }
       } 
    })