通过角度5将文件对象发送到Spring Rest控制器

时间:2018-01-16 10:50:32

标签: spring angular rest

我正在尝试在客户端上传文件并将HTTP Post请求发送到Spring Rest Controller。但是当我在Rest控制器中收到文件对象时,我可以将其视为“null”。 HTML代码:

 pattern="dd.MM.yyyy"

对应的.ts文件:

<input type="file" id="myFile" (change) = "onFileChange($event)" #fileInput>

我的春季休息控制器:

onFileChange($event) : void {
    let file:File = $event.target.files[0];
    let myReader: FileReader = new FileReader();       
    myReader.onloadend = function(e) {      
    }
    myReader.readAsText(file);
    const req = this.http.post('/abc',myReader.result, {
        headers: new HttpHeaders().set('content-type','application/pdf')
    });
    req.subscribe(
        (data) => {
            console.log(data);
        },
        (err: HttpErrorResponse) => {
            if(err.error instanceof Error) {
                //client side error
                console.log('An error occured: ',err.error.message);
            } else {
                console.log('Backend returned code', err.status, 'body was ',err.error);
            }
        }
    )
}

有人可以帮忙在这里找出问题。

2 个答案:

答案 0 :(得分:2)

尝试以下代码

HTML模板

<input type="file" id="myFile" (change)="onFileChange(fileInput.files)" #fileInput>

<强>打字稿

import { Headers, RequestOptions } from '@angular/http'; // Import header and requestOptions

//On File Select
onFileChange(files: any) {

    let file: File = files[0];

    let headers = new Headers();
    let options = new RequestOptions({ headers: headers }); // Create header

    let formData = new FormData();
    formData.append('file', file); // Append file to formdata

    const req = this.http.post('/abc', formData, options);

    req.subscribe( (data) => {

        console.log(data); // Sucess response
    }, (err: HttpErrorResponse) => {

        // Erro response
        if(err.error instanceof Error) {
          //client side error
          console.log('An error occured: ',err.error.message);
        }
        else {
          console.log('Backend returned code', err.status, 'body was ',err.error);
        }
    })
}

Spring Controller

@RequestMapping(value="/abc", method = RequestMethod.POST) 
public ResponseGenerator uploadFile(@RequestParam MultipartFile file) {

    ResponseGenerator responseGenerator = new ResponseGenerator();

    try {

        if (file != null) {
            System.out.println(file.getOriginalFilename());
        }
        return responseGenerator;
    } catch (Exception e) {
        logger.error("Error while updating user : ", e);
        return responseGenerator;
    }
}

如果您创建一个service并将http方法code放在service中,那将是更好的方法。请参阅此链接Angular 2 template form with input type=file and spring boot

答案 1 :(得分:0)

最简单的事情(根据我)是使用FormData对象。

以下是:

@viewChild() fileInput: ElementRef;

onFileChange(event) {
  const files = this.fileInput.nativeElement.files as FileList;
  const file = files.item(0);

  const formData = new FormData();
  formData.append('pdf', file, file.name);
  this.http.post('abc', formData, {
    headers: new HttpHeaders().set('content-type','application/pdf')
  }).subscribe(
    data => console.log(data),
    err => console.log(err)
  );
}

试试这个并告诉我你在Spring方面看到了什么。