我想上传带有angular和php api的pdf文件。我一直在尝试使此处(File Upload In Angular?)提出的解决方案与php api一起使用。
我测试了代码,但是没有用。
这是html文件中的代码
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
这是ts代码,我从上面放置的URL中的代码中对其进行了一些更改,以使其可与HttpClient一起使用
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new HttpHeaders();
/** In Angular 5, including the header Content-Type can invalidate your request */
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
// let options = new RequestOptions({ headers: headers });
const options = {
params: new HttpParams(),
headers: headers
};
this.Http.post(`http://localhost/Back/ajouterPublication.php`, formData, options)
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
}
这是PHP API
<?php
header("Access-Control-Allow-Origin: *");
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(array('status' => false));
exit;
}
$path = 'http://localhost//fichier';
if (isset($_FILES['file'])) {
$generatedName ='abc.pdf';
$filePath = $path.$generatedName;
if (!is_writable($path)) {
echo json_encode(array(
'status' => false,
'msg' => 'Destination directory not writable.'
));
exit;
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
echo json_encode(array(
'status' => true,
'originalName' => $originalName,
'generatedName' => $generatedName
));
}
}
else {
echo json_encode(
array('status' => false, 'msg' => 'No file uploaded.')
);
exit;
}
?>
我正在使用角度7.2.1
答案 0 :(得分:0)
您的API请求参数是uploadFile,您正在使用该文件。
将其替换为您的PHP文件。
<?php
header("Access-Control-Allow-Origin: *");
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(array('status' => false));
exit;
}
$path=$_SERVER['DOCUMENT_ROOT'] . "/your folder name/";
if (isset($_FILES['uploadFile'])) {
$generatedName ='abc.pdf';
$filePath = $path.$generatedName;
if (!is_writable($path)) {
echo json_encode(array(
'status' => false,
'msg' => 'Destination directory not writable.'
));
exit;
}
if (move_uploaded_file($_FILES['uploadFile']['tmp_name'], $filePath)) {
echo json_encode(array(
'status' => true,
'originalName' => $originalName,
'generatedName' => $generatedName
));
}
}
else {
echo json_encode(
array('status' => false, 'msg' => 'No file uploaded.')
);
exit;
}
?>