在Angular 5上上传文件并将其发送到Java Spring Back End

时间:2018-06-30 16:50:25

标签: java spring angular

我的应用程序有问题。我在Angular 5上上传了一个文件,但无法将其插入到Java Spring Back端以将其插入数据库。

尝试将frmData发送到Java Controller时收到500错误。

有人解决吗?这是我的代码:

我的组件.html:

<ng-container>
  <input type="file" id="uploadFile" multiple 
         (change)="getFileDetails($event.target.file)">
</ng-container></div>

我的组件.ts:

getFileDetails (e) {
  //console.log (e.target.files);
  for (var i = 0; i < e.target.files.length; i++) {
    this.myFiles.push(e.target.files[i]);
  }
}

addFollowUp1() {            
  const frmData = new FormData();

  for (var i = 0; i < this.myFiles.length; i++) {
    frmData.append("file", this.myFiles[i]);
  }

  this.followUpService.addFollowUpAttachment(frmData).subscribe();
}

还有我的Service.ts:

public addFollowUpAttachment(file: FormData): Observable<any> {
  return this.http.post('/SV-AUD/api/attachment/addAttachment', file );
}

在Java后端上,是控制器:

@Controller
@RequestMapping("/attachment")
public class AttachmentController {

  @Autowired
  private AttachmentService attachmentService;

  @RequestMapping(value = "/addAttachment", method = RequestMethod.POST)
  @ResponseBody
  public void addFollowUpAttachment(@RequestParam("file") MultipartFile files) throws ApcException {    
    System.out.println("test");
    attachmentService.addFollowUpAttachment(files);    
  }    
}

谢谢!

1 个答案:

答案 0 :(得分:0)

我发现了问题,而不是只使用$ event的$ event.target.file,现在我终于从Java后端xD收到了一个错误

<ng-container>
  <input type="file" id="uploadFile" multiple (change)="getFileDetails($event)">
</ng-container></div>