hi!
i’m building a js single-page app and using kirby as part of the backend.
i need to upload files through the js app, and having some problems making this work.
tl;dr my question is if im doing something wrong in receiving the file, or in sending it.
so far this is what i’m trying:
- input
<form method="post" enctype="multipart/form-data">
<input id="upload" type="file" onchange=${ upload }>
</form>
- upload function (
xhr
is this tiny library)
function upload (e) {
e.preventDefault()
const form = e.currentTarget
const file = form.files[0]
let formData = new FormData()
formData.append('module', state.page.content.title)
formData.append('file', file)
xhr({
method: 'post',
headers: {'Content-Type': undefined},
url: '/apiupload',
body: formData,
}, function (err, resp, body) {
if (err) throw err
console.log(err, resp, body)
})
}
- kirby plugin
<?php
Kirby::plugin('mooc/upload', [
'routes' => [
[
'method' => 'POST',
'pattern' => 'apiupload',
'action' => function () {
if(r::is('POST')) {
$data = array(
'module' => get('module'),
'file' => get('file')
);
$p = page('error')->children()->create(str::slug(time()), 'assignment', $data);
return response::json($data);
}
}
]
]
]);
using this answer as guidance.
the file never gets sent through. i can get the string value from 'module' => get('module'),
, but never that of file.
i read you should not set the headers: content-type
in the js post call, or set them to undefined. in either case, it does not change.
also, should i use GET
or POST
in the 'method' => type
? i think GET, as im fetching something from an endpoint, but im still too noob and confused about these stuff to be sure
any hint? thanks!