对于发送多个文件,我做了一点不同,因为我的 php api 端点说如果我发送它只有一个文件formdata.append('files[]', file)
<input type="file" multiple data-sender="{{ user.hashIdentifier }}">
/** @type {HTMLInputElement} */
const input = document.querySelector('input[type=file]');
input.addEventListener('input', function listener(event){
if(input.files.length > 0){
const formData = new FormData();
for(let i = 0; i < input.files.lenght; i++){
formData.append(`file_${i}`, input.files[i]);
}
// my endpoint should know who sends the file
formData.append('identify', input.dataSet.sender);
sendData(formData);
} else {
console.error('no files selected');
}
});
/**
* sending the formData Object with all files to the server
* @param {FormData} formData
*/
function sendData(formData) {
const url = '/api/saveFiles';
const options = {
method: 'POST',
body: formData
};
fetch(url, options)
.fetch((response) => {
if(!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.fetch((data) => {
console.log('success', data);
})
.catch((error) => {
console.error(error);
})
}
我的 php 是一个 symfony 项目,看起来像这样:
/**
* @param Request $request (inject symfonys http request)
* @param FileService $fileService (inject my own FileService)
* @returns Response (symfony http Response)
*/
#[Route('/api/saveFiles', name: 'api_saveFiles', methods: ['POST'])]
public function api_saveFiles(Request $request, FileService $fileService): Response
{
$statusCode = 409; // Conflict
$result = array();
/** @var FileBag */
$fileBag = $request->files;
if($fileBag->count() > 0) {
$statusCode=200;
$result['numberOfFiles'] = $fileBag->count();
$result['keys'] = $fileBag->keys();
$result['infos'] = array();
foreach($fileBag->keys() as $key){
try {
$file = $fileBag->get($key);
$fileInfo = $fileService->saveFile($file); // saves the file and gives back some infos
$result['infos'][$fileInfo];
} catch(Exception $ex) {
// TODO: handle errors
}
}
}
return new JsonResponse($result, $statusCode);
}
在尝试中,我尝试使用formData.append('files[]', file);
php 只捕获了最后一个文件。