【发布时间】:2022-01-19 17:05:35
【问题描述】:
我正在从 Angular 13.0.4 向我的 Laravel 8 控制器发送一个图像文件,但该文件无法识别 通过 Laravel。就像什么都不发送一样。
当我尝试 Postman 或 Insomnia 时,它工作得非常好。
我的Laravel Controller是这样的:
public function uploadimage(Request $request)
{
if ($request->hasFile('image'))
{
return response()->json(["message" => "A file was sent!"]);
}
else
{
return response()->json(["message" => "No file sent!"]);
}
}
Postman 返回文件已发送!,白色 Angular 返回未发送文件!
我的 Courses.component.ts 是这样的:
export class CoursesComponent {
constructor(private http:HttpClient) { }
filedata:any;
/* File onchange event */
fileEvent(e:any){
this.filedata = e.target.files[0];
}
/* Upload button functioanlity */
onSubmitform(f: NgForm) {
var myFormData = new FormData();
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
myFormData.append('image', this.filedata);
/* Image Post Request */
this.http.post('http://fener.tachyonstudio.com/api/sample-restful-apis', myFormData, {
headers: headers
}).subscribe(data => {
console.log(data);
});
}
而我的Courses.component.html是这样的:
<form #f="ngForm" (ngSubmit)="onSubmitform(f)" enctype='multipart/form-data'>
<input type="file" name="image" (change)="fileEvent($event)"/>
<button>Upload Image</button>
</form>
我是 Angular 的新手,所以我被困在这里很长一段时间了。
【问题讨论】: