gpt4 book ai didi

javascript - Angular2 中的文件上传不起作用

转载 作者:行者123 更新时间:2023-12-03 04:26:45 25 4
gpt4 key购买 nike

我正在尝试创建一个文件上传功能,用户可以在其中上传geotiff(大小可能有几GB)。由于某种原因,我的 Angular 代码无法访问 api 并抛出 404,但我可以使用 Postman 上传文件。

Angular 代码:

 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 });
}

最佳答案

我了解到 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);
}
});
}

关于javascript - Angular2 中的文件上传不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43672903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com