[英]Angular failed to upload file
這是我用來上傳文件的一堆后端代碼。
$app->post('/upload/{studentid}', function(Request $request, Response $response, $args) {
$uploadedFiles = $request->getUploadedFiles();
// handle single input with single file upload
$uploadedFile = $uploadedFiles['filename'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
// ubah nama file dengan id buku
$filename = sprintf('%s.%0.8s', $args["studentid"], $extension);
$directory = $this->get('settings')['upload_directory'];
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
// simpan nama file ke database
$sql = "UPDATE feepaid SET filename=:filename WHERE studentid=:studentid";
$stmt = $this->db->prepare($sql);
$params = [
":studentid" => $args["studentid"],
":filename" => $filename
];
if($stmt->execute($params)){
// ambil base url dan gabungkan dengan file name untuk membentuk URL file
$url = $request->getUri()->getBaseUrl()."/Upload/".$filename;
return $response->withJson(["status" => "success", "data" => $url], 200);
} else {
return $response->withJson(["status" => "failed", "data" => "0"], 200);
}
}
});
當我使用郵遞員測試它的工作時,但我對 Angular 很陌生。 當我在我的 Angular 應用程序中實現 api 時它不起作用
這是我用來從 angular 應用程序上傳文件的代碼
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();
/** In Angular 5, including the header Content-Type can invalidate your request */
// headers.append('Content-Type', 'multipart/form-data');
// headers.append('Accept', 'application/json');
const id = sessionStorage.getItem('userId');
// const options = new RequestOptions({ headers: headers });
this.http.post('http://localhost:8080' + '/upload/' + id , formData)
.subscribe(
data => console.log('success'),
error => console.log(error)
);
}
}
這是我使用 Postman 進行測試的示例
為什么我有錯誤? 好像我的文件沒有發送到后端,它的返回空值。 任何人都可以幫助我嗎? 謝謝
當您將鍵作為filename
檢索時,您需要發送表單數據的確切鍵值對,因此請嘗試更改:
formData.append('filename', file, file.name);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.