【发布时间】:2019-03-12 04:32:25
【问题描述】:
我有这个表格,我需要能够通过 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?还是我只需要它来拍摄照片?我还没有尝试做这两件事,任何指导将不胜感激。
【问题讨论】:
-
你所有的数据都需要在一个formData对象中
-
在我这样做之后,我只需发送保存 FormData() 的变量和 axios 之类的数据:formdata?
-
是的,没错
-
@Paras 不幸的是,我已经这样做了,最终我将一个空对象发送到服务器。
标签: javascript json ajax laravel file-upload