首页 > 解决方案 > 如何使用 vanilla javascript 通过 ajax 将多张照片上传到 Laravel 应用程序?

问题描述

我有这个表单,我需要能够通过 ajax 将数据发布到服务器,用户可以上传 1 张或多张照片,或者他们可能根本不上传任何照片,无论如何我如何发送从 `type 获取的数据=文件输入并在后台上传到服务器?

这是表格的相关部分:

<form action="" method="POST" enctype="multipart/form-data">
            @csrf
                <label for="photos">Photos:</label>
                <input type="file" name="photos[]" id="photos" class="form-control" multiple>


                <button class="btn btn-success mt-3" onclick="ajaxify(event)">Submit</button>
            </div>
        </form>

这是javascript的相关部分:

function ajaxify(event) {
            event.preventDefault();
            let failedValidation = false;

           // I removed parts of the code where I load other dataand do validation, irrelevant to the question.

            let photos = [];


            if(document.getElementById('photos').value !== '') {
                photos = document.getElementById('photos');   // I know this is incorrect, but I don't know what to do here.
            }

           // Here photos.value return something like c://fake/filename
           // And it doesn't return more than 1 file even, so anyway I am definitely doing this wrong.


            if(! failedValidation) {
                axios.post('/listing/create', {
                    client_name: name.value,
                    client_phone_number: client_phone_number.value,
                    category: category.value,
                    type: type.value,
                    governorate: governorate.value,
                    city: city.value,
                    space: space.value,
                    price: price.value,
                    furnished_status: furnished_status.value,
                    payment_type: payment_type.value,
                    initial_deposit: initial_deposit.value,
                    monthly_amount: monthly_amount.value,
                    notes: notes.value,
                    photos: photos.value, // So this should be an array of uploaded files.
                })
                .then((resp) => {
                    invalid.classList.add('d-none');
                    console.log(resp);
                })
            }
        }

我想要什么?是让我上传的文件在应用程序的服务器端可用于 Laravel,当我做一个普通的帖子并且dd($request->photos);我得到一个上传文件的数组时,我不确定 ajax/json 是否有可能与否,但这就是我想要处理照片的目的。

快速说明一下,如果这有什么不同,我正在使用 Laravel 媒体库包。

到目前为止我所做的是研究此事,我读到我需要使用FormData(),我以前从未使用过它,我有几个问题,我是否需要将我的所有数据放入该FormData()对象并提供到axios?还是我只需要它来拍摄照片?我还没有尝试做这两件事中的任何一个,任何指导将不胜感激。

标签: javascriptjsonajaxlaravelfile-upload

解决方案


您只会得到一个文件,因为所有文件对象都存储在files属性的数组中。只需将它们附加到您的photos数组中即可。

function ajaxify(event) {
  event.preventDefault();

  // use files attribute to get an array of the files
  var photoFiles = document.getElementById("photos").files;

  // using the array of files, create an array 'photos' of FormData objects
  let photos = [];
  for (let photo of photoFiles) {
    photos.push(new FormData(photo);
  }

  // turn your 'photos' array into a javascript object
  let photos = arr2obj(photoFiles);

  // this should fix the empty array problem you were having
  // pass 'photos' to the ajax data

  // ....
}

编辑:根据这篇文章FormData,正如其中一位评论者指出的那样,使用 AJAX 上传文件需要一个对象。您的数组必须是FormData对象数组。

编辑:通过 JSON 发送数组很麻烦。把你的数组变成一个对象。您可以使用像这样的简单函数从数组中构建一个对象。

function arr2obj(arr) {
  var obj = {};
  for (let i=0; i<arr.length; i++) {
    obj['photo'+i] = arr[i];
  }
  return obj;
}

推荐阅读