Below is the backend code snippet used to upload a file:
$app->post('/upload/{studentid}', function(Request $request, Response $response, $args) {
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['filename'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
$filename = sprintf('%s.%0.8s', $args["studentid"], $extension);
$directory = $this->get('settings')['upload_directory'];
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
$sql = "UPDATE feepaid SET filename=:filename WHERE studentid=:studentid";
$stmt = $this->db->prepare($sql);
$params = [
":studentid" => $args["studentid"],
":filename" => $filename
];
if($stmt->execute($params)){
$url = $request->getUri()->getBaseUrl()."/Upload/".$filename;
return $response->withJson(["status" => "success", "data" => $url], 200);
} else {
return $response->withJson(["status" => "failed", "data" => "0"], 200);
}
}
});
I have tested this using Postman and it worked fine. However, when implementing the API in my Angular application, I encountered some issues.
You can view my Angular file upload code below:
fileChange(event) {
const fileList: FileList = event.target.files;
if (fileList.length > 0) {
const file: File = fileList[0];
const formData: FormData = new FormData();
formData.append('uploadFile', file, file.name);
const headers = new Headers();
const id = sessionStorage.getItem('userId');
this.http.post('http://localhost:8080' + '/upload/' + id , formData)
.subscribe(
data => console.log('success'),
error => console.log(error)
);
}
}
If you encounter any errors or have suggestions, please feel free to reach out. Your assistance would be greatly appreciated!