【问题标题】:Upload Multiple images in Laravel using Vue.js使用 Vue.js 在 Laravel 中上传多张图片
【发布时间】:2021-02-06 09:20:08
【问题描述】:

我正在尝试在 Laravel 中使用 vue.js 上传图片,因为我正在使用此链接

https://jsfiddle.net/b412ruzo/

使用 vue.js 上传图片,当我提交表单时,我在 files 数组中得到以下图片

现在的问题是我无法在 laravel 控制器中获取此文件数组

当我打印时

$request->file('files') 

在我的控制器中,我得到了空值。 当我打印 $request->input('files') 这是结果,一个空数组

非常感谢有关此问题的任何帮助。

代码片段:

data() {
     return {
    rawData: [],
    formData: new Form({
        files:[],
})
..

  const header = {
             Authorization: "Bearer " + this.token,
            };
  this.formData
        .post(APP_URL + `/api/post`, { headers: header })
        .then((response) => {

   }

【问题讨论】:

  • 在发送文件的地方添加 ajax 代码
  • @KamleshPaul:添加了代码 sn-p,请检查,我可以检索其他字段值,但问题仅针对图像
  • 你为什么不使用 axios .?
  • @KamleshPaul:这是旧代码,以前图像是用插件上传的,但现在我想用自定义函数上传它。

标签: javascript laravel vue.js laravel-5


【解决方案1】:

不确定是否可以通过 this.formData.post 发送 ajax 请求

试试这个

new Vue({
  el: "#app",
  data() {
    return {
      option: {
        maxFileCount: 3
      },
      files:[],
      rawData: [],
    }
  },
  methods: {
    loaddropfile: function(e) {
        e.preventDefault()
      e.stopPropagation()
        alert('ok')
        console.log(e)
    },
    openinput: function() {
        document.getElementById("vue-file-upload-input").click();
    },
    addImage: function(e) {
        const tmpFiles = e.target.files
      if (tmpFiles.length === 0) {
        return false;
      }
      const file = tmpFiles[0]
      this.files.push(file)
      const self = this
        const reader = new FileReader()
      reader.onload = function(e) {
        self.rawData.push(e.target.result)
      }
      reader.readAsDataURL(file)
    },
    removeFile: function(index) {
        this.files.splice(index, 1)
      this.rawData.splice(index, 1)
      document.getElementById("vue-file-upload-input").value = null
    },
    upload: function() {
        alert('Check console to see uploads')
        console.log(this.files)
      axios.post(`${APP_URL}/api/post`,{files:this.files},{ headers: header })
        .then((response) => {});

    }
  },
  mounted(){

  }
})

它会将您的表单数据发送到files 键,以便您可以通过$request->file('files') 获取所有文件

【讨论】:

  • 我收到消息:“未经身份验证。”使用 axios 后出现 401
  • 我有有效的令牌 {Authorization: "Bearer Gx6j7U4No1P73jKawvV0KjXIFRiYG8eoSJsZVtBcksA…meIMTD5XBaIpCooIA9C8RBsEOsjTBLlrGhQp04m7nKNelnAHy"} 当我删除 axios 时它可以工作
  • 尝试使用 axios 在 dd($request->file('files')); 中也得到空值;
  • 试试dd($request->all());
  • 添加了输出,它为文件字段返回相同的结果,但获取其他字段上述小提琴链接中提供的 Vue.js 代码是否有任何问题
猜你喜欢
  • 2021-08-06
  • 2015-04-23
  • 2020-10-07
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
  • 2021-12-22
  • 1970-01-01
  • 2019-09-05
相关资源
最近更新 更多