[英]How can I upload multiple photos to a Laravel application through ajax using vanilla javascript?
我有这个表格,我需要能够通过ajax将数据发布到服务器,用户可以上传1张或更多照片,或者他们可能根本不上传任何照片,无论如何我都可以发送从`类型中获取的数据=文件输入并在后台将其上传到服务器?
这是表格的相关部分:
<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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.