以angular2发送文件

时间:2016-12-06 12:49:59

标签: java http spring-mvc angular

我需要在我的网络应用程序中通过POST发送文件。我在java中有一个服务器端,在角度2中有一个客户端。我需要客户端将文件发送到服务器。服务器代码:

@RequestMapping(method = RequestMethod.POST, value = "/run/file")
@ResponseBody
private void runImportRecordsJob(@RequestParam("file") MultipartFile file){
    // Some code
}

客户代码:

组件:

export class ImportRecordsJobComponent implements OnInit {

  file: File;


  constructor(private jobsService: JobsService) { }


  chooseFile(event: any){
    this.file = event.srcElement.files[0];

    console.log(this.file);
  }

  selectFormat(event: any){
    if (event.length > 0)
      this.format = event[0].key;
    else
      this.format = null;

  }

  runImportRecordsJob(){
    if (confirm("Are you sure you want to run this job?")){
      this.jobsService.runImportRecordsJob({file: this.file});
    }
  }

  ngOnInit() {
  }

}

服务:

@Injectable()
export class JobsService {

  constructor(private http: Http) { }

  runImportRecordsJob(importRecords: any){
    var headers = new Headers({"Content-Type": 'application/json; multipart/form-data;'});
    let options = new RequestOptions({ headers: headers });

    let formData = new FormData();
    formData.append("file", importRecords.file, importRecords.file.name);

    this.http.post(SERVER + "/batches/run/file", formData, options).subscribe();
  }

}

但我收到了一个错误:nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request

并且formData始终为空。任何人都可以建议我如何发送文件而不使用ng2-uploader和类似的东西。感谢。

1 个答案:

答案 0 :(得分:1)

你错过了" CommonsMultipartResolver"豆?

<bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 20 * 1024 * 1024 Byte = 20 MB-->
        <property name="maxUploadSize" value="20971520" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

修改

更改了服务上的方法:

  runImportRecordsJob(importRecords: any){
    let options = new RequestOptions();

    let formData = new FormData();
    formData.append("file", importRecords.file, importRecords.file.name);

    console.log(formData);
    console.log(importRecords);
    this.http.post(SERVER + "/batches/run/file", formData, options).subscribe();
  }