使用Angular2将文件上传到REST API

Sla*_*ter 50 spring spring-mvc angular2-forms angular2-http angular

实际上,我正在使用一个以Angular 2编码的接口的Spring REST API.

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

我在java中的Webresources是这样的:

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

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

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

在此输入图像描述 我加了

<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
Run Code Online (Sandbox Code Playgroud)

Spring配置文件和Pom依赖项

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用webform执行相同的操作时:

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

使用(更改)方法:

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'));
    */
}
Run Code Online (Sandbox Code Playgroud)

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

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

有人可以帮我弄清问题是什么?

问题解决了,我稍后会用我的代码更新这个问题:)但是,看一下它的工作得很好.谢谢.

Bro*_*row 156

这在最终版本中实际上很容易实现.我花了一段时间来绕过它,因为我遇到的关于它的大部分信息已经过时了.在这里发布我的解决方案以防其他人正在努力解决这个问题.

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后就像这样使用它:

<file-upload #fu (change)="fu.upload()" [multiple]="true"></file-upload>
Run Code Online (Sandbox Code Playgroud)

这就是它的全部内容.

或者,捕获事件对象并从srcElement获取文件.老实说,不确定是否有任何方式比另一方更好!

请记住FormData是IE10 +,所以如果你必须支持IE9,你需要一个polyfill.

更新2017-01-07

更新了代码,以便能够处理多个文件的上传.另外我的原始答案是缺少一个关于FormData的相当重要的一点(因为我将实际的上传逻辑移动到我自己的应用程序中的一个单独的服务,我在那里处理它).

  • 当然!但是,当您搜索"有角度的2文件上传"时,这个问题是第一个出现在Google上的问题.想想我会添加一些最新信息. (36认同)
  • 如果有人想知道FormData来自哪里,它的原生FormData对象:https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData你不需要导入任何东西. (4认同)
  • 你在哪个版本的RC?有没有其他人成功使用它?似乎不适合我. (2认同)
  • 这很棒!一个警告 - 确保不要手动设置Content-Type标头.保留未指定,Angular 2似乎选择了正确的值,至少在application/json和multipart/form-data之间 (2认同)

Thi*_*ier 26

事实上,在那一刻,你只能提供字符串输入post,putpatch在Angular2 HTTP支持的方法.

为了支持这一点,您需要直接利用XHR对象,如下所述:

import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class UploadService {
  constructor () {
    this.progress$ = Observable.create(observer => {
      this.progressObserver = observer
    }).share();
  }

  private makeFileRequest (url: string, params: string[], files: File[]): Observable {
    return Observable.create(observer => {
      let formData: FormData = new FormData(),
        xhr: XMLHttpRequest = new XMLHttpRequest();

      for (let i = 0; i < files.length; i++) {
        formData.append("uploads[]", files[i], files[i].name);
      }

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            observer.next(JSON.parse(xhr.response));
            observer.complete();
          } else {
            observer.error(xhr.response);
          }
        }
      };

      xhr.upload.onprogress = (event) => {
        this.progress = Math.round(event.loaded / event.total * 100);

        this.progressObserver.next(this.progress);
      };

      xhr.open('POST', url, true);
      xhr.send(formData);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此plunkr:https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p = info .

在Angular回购中有一个问题和待决公关:


Ani*_*mal 12

这对我有用:

<input type="file" (change)="onChange($event)" required class="form-control " name="attach_file" id="attach_file">
onChange(event: any) {
    let fileList: FileList = event.target.files;
if(fileList.length > 0) {
    let file: File = fileList[0];
    let formData:FormData = new FormData();
    formData.append('degree_attachment', file, file.name);
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    this.http.post('http://url', formData,options)
        .map(res => res.json())
        .catch(error => Observable.throw(error))
        .subscribe(
            data => console.log('success'),
            error => console.log(error)
        )
}}
Run Code Online (Sandbox Code Playgroud)


hem*_*123 5

这对我有用:Angular 2为上传文件提供了很好的支持:

<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();
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        this.http.post(URL, formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)
            )
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到了错误: java.io.IOException: RESTEASY007550: Unable to get boundary for multipart

为了解决这个问题,你应该删除"Content-Type""multipart/form-data"