使用Angular 7向服务器提交图像文件与其他表单数据一起提交



我已经提交了车辆的详细信息,包括VIN,驾驶员和车辆照片。我的问题是将表单数据详细信息与图像一起提交到服务器上,以我的后端作为我的后端

uploadImage (e) {     
for (let i = 0; i < e.target.files.length; i++)
       {
  this.selectedFile = <File>e.target.files[i];
       }
  }
onSubmit(){  //this method is called when user submits data
const fd = new FormData();
     fd.append('file', this.selectedFile, this.selectedFile.name);
         this.http.post('http://localhost:8000/api/buses',
         {fd, 'formdata':this.form}).subscribe((data)=>console.log(data))
}
//this is the code receiving the image
 if($request->has('file')) {
    // Get filename with the extension
    $filenameWithExt = $request->file('file')->getClientOriginalName();
    // Get just filename
    $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
    // Get just ext
    $extension = $request->file('file')->getClientOriginalExtension();
    // Filename to store
    $fileNameToStore = $filename . '_' . time() . '.' . $extension;
    // Upload Image
    $path = $request->file('file')->storeAs('public/cover_images', $fileNameToStore);
echo json_encode($fileNameToStore);

}

将图像和其他formdata提交给我的后端服务器

您发布了错误的信息。请按以下方式更改此内容。

fd.append('file', this.selectedFile, this.selectedFile.name);
         this.http.post('http://localhost:8000/api/buses',
         fd).subscribe((data)=>console.log(data))

最新更新