如何使用vanilla javascript通过ajax将多张照片上传到Laravel应用程序?



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

以下是表单的相关部分:

<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?还是我只需要它来拍照?我还没有尝试做这两件事中的任何一件事,任何指导都将不胜感激。

您只得到一个文件,因为所有文件对象都存储在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
// ....
}

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

编辑:通过JSON发送数组很麻烦。将数组转换为对象。您可以使用这样的简单函数从数组中构建对象。

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

最新更新