我正在尝试使我的Ionic应用程序上传用户选择的图像。我阅读了几个教程,但是我没有设法使它工作。我希望应用程序在浏览器中运行,因此我没有实现仅在移动平台上运行的解决方案。
我的 angular 组件将发布请求发送到托管以下 php 脚本的服务器,并按指定创建“uploads”文件夹。但是每次我想上传我的文件时,我都会收到“上传文件时出错,请重试!”消息,在我的PHP脚本中指定。
我想我可能以错误的格式发送数据,但是可以弄清楚该怎么做。
任何想法,我的问题可能是什么?
<?php
header('Access-Control-Allow-Origin: *');
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
header('Content-type: application/json');
$data = ['success' => true, 'message' => 'Upload and move success'];
echo json_encode( $data );
} else{
header('Content-type: application/json');
$data = ['success' => false, 'message' => 'There was an error uploading the file, please try again!'];
echo json_encode( $data );
}
?>
这是我的组件中的类型脚本代码:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-erledigt-modal',
templateUrl: './erledigt-modal.component.html',
styleUrls: ['./erledigt-modal.component.scss'],
})
export class ErledigtModalComponent implements OnInit {
constructor(private http: HttpClient) { }
selectedFile = null;
ngOnInit() {
}
onFileChanged(event) {
this.selectedFile = <File>event.target.files[0]
}
onUpload() {
const uploadData = new FormData();
uploadData.append('image', this.selectedFile, this.selectedFile.name);
this.http.post('https://...MyAPI.../upload.php', uploadData).subscribe(res => {
console.log(res);
});
}
}
我还尝试了以下POST请求,但没有成功:
this.http.post('https://...MyAPI.../upload.php', this.selectedFile).subscribe(res => {
console.log(res);
});
}
我的 HTML 看起来很简单:
<input type="file" (change)="onFileChanged($event)">
<button type="button" (click)="onUpload()">Upload</button>
慕容森