温馨提示:本文翻译自stackoverflow.com,查看原文请点击:spring - File Upload with Angular2 to REST API
angular spring spring-mvc angular2-forms angular2-http

spring - 使用Angular2将文件上传到REST API

发布于 2020-03-30 21:41:31

实际上,我正在使用带有Angular 2编码的接口的Spring REST API。

我的问题是我无法使用Angular 2上传文件。

我在Java中的Webresources是:

@RequestMapping(method = RequestMethod.POST, value = "/upload")
public String handleFileUpload(@RequestParam MultipartFile file) {
    //Dosomething 
}

当我通过带有Auth标头等的URL请求调用它时(它具有适用于Chrome的Advanced Rest Client扩展),它完全可以正常工作

证明:(在这种情况下,一切正常)

在此处输入图片说明 我添加了

<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

Spring配置文件和Pom依赖

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2</version>
</dependency>

但是,当我尝试使用网络表单执行相同的操作时:

<input type="file" #files (change)="change(files)"/>
<pre>{{fileContents$|async}}</pre>

使用(change)方法:

change(file) {
    let formData = new FormData();
    formData.append("file", file);
    console.log(formData);
    let headers = new Headers({
        'Authorization': 'Bearer ' + this.token,
        'Content-Type': 'multipart/form-data'
    });
    this.http.post(this.url, formData, {headers}).map(res => res.json()).subscribe((data) => console.log(data));
    /*
    Observable.fromPromise(fetch(this.url,
        {method: 'post', body: formData},
        {headers: this.headers}
    )).subscribe(()=>console.log('done'));
    */
}

我的Web服务向我返回错误500,并在tomcat日志中显示该错误:http : //pastebin.com/PGdcFUQb

我也尝试过该'Content-Type': undefined方法,但没有成功(在这种情况下,Web服务向我返回415错误。

有人可以帮助我找出问题所在吗?

问题已解决,我将在稍后用我的代码更新该问题:),但是,请看一下它工作得很好的插件。谢谢。

查看更多

提问者
Slater
被浏览
83
Brother Woodrow 2017-02-18 23:19

在最终版本中,这实际上很容易做到。花了我一些时间来解决这个问题,因为我遇到的有关它的大多数信息都已过时。如果其他人为此感到困扰,请在此处发布我的解决方案。

import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'file-upload',
    template: '<input type="file" [multiple]="multiple" #fileInput>'
})
export class FileUploadComponent {
    @Input() multiple: boolean = false;
    @ViewChild('fileInput') inputEl: ElementRef;

    constructor(private http: Http) {}

    upload() {
        let inputEl: HTMLInputElement = this.inputEl.nativeElement;
        let fileCount: number = inputEl.files.length;
        let formData = new FormData();
        if (fileCount > 0) { // a file was selected
            for (let i = 0; i < fileCount; i++) {
                formData.append('file[]', inputEl.files.item(i));
            }
            this.http
                .post('http://your.upload.url', formData)
                // do whatever you do...
                // subscribe to observable to listen for response
        }
    }
}

然后像这样使用它:

<file-upload #fu (change)="fu.upload()" [multiple]="true"></file-upload>

这就是全部。

或者,捕获事件对象并从srcElement获取文件。老实说,不确定是否有任何方法比其他方法更好!

请记住,FormData是IE10 +,因此,如果必须支持IE9,则需要使用polyfill。

更新2017-01-07

更新了代码以能够处理多个文件的上载。另外,我最初的答案缺少有关FormData的相当关键的一点(因为我将实际的上载逻辑移到了我在自己的应用程序中处理的单独服务中)。