Angular2中的文件上传无效

时间:2017-04-28 05:51:36

标签: javascript c# angular file-upload .net-core

我正在尝试创建一个文件上传功能,用户可以上传geotiff(大小可能是几GB)。 出于某种原因,我的角度代码无法点击api并抛出404,但我可以使用Postman上传文件。

Angular Code:

 fileChange(event) {
        let token = localStorage.getItem('userToken');
        let fileList: FileList = event.target.files;
        if (fileList.length > 0) {
            let file: File = fileList[0];
            let formData: FormData = new FormData();
            formData.append('files', file, file.name);
            let headers = new Headers();
            headers.append('Content-Type', 'multipart/form-data');
            headers.append("Authorization", token);
            let options = new RequestOptions({ headers: headers });
            this.uploadInProgress = true;
            this._http.post(`${this.uploadApiUrl}`, formData, options)
                .map(res => res.json())
                .catch(error => Observable.throw(error))
                .subscribe(
                data => console.log('success'),
                error => console.log(error),
                () => this.uploadInProgress = false)
        }
    }

API:

// POST: api/GeoTif
[HttpPost]
public async Task<IActionResult> Post(List<IFormFile> files)
        {
            long size = files.Sum(f => f.Length);


            return Ok(new { NoOfUploadedFileCount = files.Count, TotalFileSize =size });
        }

2 个答案:

答案 0 :(得分:1)

我知道HTTP服务和FormData存在问题..您可以使用XMLHttpRequest来完成它:

fileChange(event: Event) {
    this.uploadFile(event)
        .subscribe(() => {
            console.log('sent');
        })
}

private uploadFile(event: Event) {
    return Observable.create(observer => {
        const token = localStorage.getItem('userToken');
        const fileList = event.target.files;
        if (fileList.length > 0) {
            const file = fileList[0];
            const formData = new FormData();
            const xhr = new XMLHttpRequest();

            formData.append('files', file, file.name);
            this.uploadInProgress = true;
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        observer.next(JSON.parse(xhr.response));
                        observer.complete();
                    } else {
                        observer.error(xhr.response);
                    }
                    this.uploadInProgress = false;
                }
            }

            xhr.open('POST', this.uploadApiUrl, true);
            xhr.send(formData);
        }
    });
}

答案 1 :(得分:0)

使用public Scene soot_Scene() { if(this.instance_soot_Scene == null) { synchronized(this) { if(this.instance_soot_Scene == null) { this.instance_soot_Scene = new Scene(this.g); } } } return this.instance_soot_Scene; } 添加您的网址(例如:http://)。 并删除以下代码。

http://localhost/api/GeoTif/