[英]Sending file from Angular to Laravel
I'm sending an image file from Angular 13.0.4 to my Laravel 8 controller, but this file is not recognized by 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 的新手,所以我被困在這里很長一段時間了。
嘗試使用enctype
而不是Content-Type
所以替換你的:
headers.append('Content-Type', 'multipart/form-data');
經過
headers.append('enctype', 'multipart/form-data');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.