【问题标题】:Spring Angular 4 upload image?Spring Angular 4上传图片?
【发布时间】:2018-02-22 23:01:12
【问题描述】:

如何用 Angular 4 上传图片?

<input type="file" (change)="uplod($event)"/>

弹簧代码:

@RequestMapping(value="/Etablissement/upload", method=RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
    File convertFile = new File("C:/Users/acer/reservationF/reservation/reservation/image"+file.getOriginalFilename());
    convertFile.createNewFile();
    FileOutputStream fout = new FileOutputStream(convertFile);
    fout.write(file.getBytes());
    fout.close();
    return new ResponseEntity<>("File is uploaded successfully", HttpStatus.OK);
}

【问题讨论】:

标签: spring angular spring-data-jpa


【解决方案1】:

试试这个代码。这对我有用。您不必为此方法导入任何外部库。

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">

fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        /** No need to include Content-Type in Angular 4 */
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        this.http.post(`${this.apiEndPoint}`, formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)
            )
    }
}

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 2018-10-04
      • 2019-04-15
      • 2017-11-15
      相关资源
      最近更新 更多