[英]Angular - upload file as base64
我正在尝试将文件从Angular 4应用程序上传到接受base64字符串作为文件内容的JSON API服务。
所以我要做的是-使用FileReader.readAsDataURL
读取文件,然后当用户确认上传时,我将向API创建一个JSON请求并发送我之前获取的文件的base64
字符串。
这是问题开始的地方-一旦我对“内容”(将其记录,发送,发送)执行某项操作,请求将被发送,但是它的速度非常慢,例如2MB文件需要20秒。
我试过了:
ArrayBuffer
并将其手动转换为base64 @angular/common
的旧客户端 但一切都会导致相同的结果。
我知道问题出在哪里。 但是为什么会发生呢? 它是特定于浏览器还是特定于角度的? 有没有更喜欢的方法(请记住,它必须是base64字符串)?
笔记:
码:
当用户将文件添加到放置区时,此方法运行:
public onFileChange(files: File[]) : void {
files.forEach((file: File, index: number) => {
const reader = new FileReader;
// UploadedFile is just a simple model that contains filename, size, type and later base64 content
this.uploadedFiles[index] = new UploadedFile(file);
//region reader.onprogress
reader.onprogress = (event: ProgressEvent) => {
if (event.lengthComputable) {
this.uploadedFiles[index].updateProgress(
Math.round((event.loaded * 100) / event.total)
);
}
};
//endregion
//region reader.onloadend
reader.onloadend = (event: ProgressEvent) => {
const target: FileReader = <FileReader>event.target;
const content = target.result.split(',')[1];
this.uploadedFiles[index].contentLoaded(content);
};
//endregion
reader.readAsDataURL(file);
});
}
用户单击“保存”按钮时运行此方法
public upload(uploadedFiles: UploadedFile[]) : Observable<null> {
const body: object = {
files: uploadedFiles.map((uploadedFile) => {
return {
filename: uploadedFile.name,
// SLOWDOWN HAPPENS HERE
content: uploadedFile.content
};
})
};
return this.http.post('file', body)
}
为了将大文件发送到服务器,您应该使用FormData
使其能够作为多部分发送,而不是单个大文件。
就像是:
// import {Http, RequestOptions} from '@angular/http'; uploadFileToUrl(files, uploadUrl): Promise<any> { // Note that setting a content-type header // for mutlipart forms breaks some built in // request parsers like multer in express. const options = new RequestOptions(); const formData = new FormData(); // Append files to the virtual form. for (const file of files) { formData.append(file.name, file) } // Send it. return this.http.post(uploadUrl, formData, options); }
另外,不要忘记设置标题'Content-Type': undefined
,我已经花了好几个小时摸索了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.