1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > angular 上传图片 上传文件 将文件转base64编码和二进制编码上传

angular 上传图片 上传文件 将文件转base64编码和二进制编码上传

时间:2022-08-08 16:32:01

相关推荐

angular 上传图片 上传文件 将文件转base64编码和二进制编码上传

angular 上传图片,上传文件

提示

虽然题目说是angular的,但是其实js,和vue的也可以用,因为之前学angular的时候,那时候还不太熟js,网上关于上传文件的东西找了很久,很难受,所以为了方便初学者,现在自己也写一篇用angular上传文件的文章。

html文件上就不搞那些花里胡哨的东西了

html

<input type="file" id="file" (change)="getfiledata($event)" multiple><button id="uploadfile" (click)="postfile()">点击上传</button>

上面input后面的multiple是可以上传多个文件的属性,加不加随你,不加就每次就只能选一张图片或文件,标签的id可以随便取,后面的ts文件会用到。

compon.ts文件

export class UploadFileComponent implements OnInit {constructor(private api: UploadFileService) {}public filesdata: Filedata[] = []public alarm: string[] = []public fileBase64: stringpublic fileBinary: stringreader = new FileReader()ngOnInit() {}getfiledata(event) {this.filesdata=[]this.alarm = []var getfile = <HTMLInputElement>document.getElementById('file') //获取html文件上id为“file”的input标签的值for (var i = 0; i < getfile.files.length; i++) {this.transformFile(getfile.files[i])}console.log(this.fileBase64) //可以在浏览器上看到文件转成的base64编码}transformFile(getfile: any) {let reader = new FileReader();reader.readAsDataURL(getfile);reader.onload = () => {this.fileBase64 = <string>reader.result //读取该文件base64编码this.fileBinary = atob(this.fileBase64.substring(this.fileBase64.indexOf(',') + 1))//将base64转为二进制编码let data = {fileName: getfile.name,fileBinary: this.fileBinary,fileBase64: this.fileBase64}this.filesdata.push(data) }}public postfile() {// 传递选中的标题回服务器 this.api.postimage(this.filesdata).subscribe(() => {});}}

很多人喜欢将http请求直接写在component.ts文件里面,但这样是不标准的,在angular官方文档里,这些服务都是分开写的,要写在特定的service.ts文件里,具体怎么创建service我就不讲了

service.ts

import {Injectable } from '@angular/core';import {HttpClient, HttpHeaders } from '@angular/common/http';import {Observable } from 'rxjs';import {Filedata } from './filedata'const httpOptions = {headers: new HttpHeaders({'Content-Type': 'application/json'})};@Injectable({providedIn: 'root'})export class UploadFileService {constructor(private http: HttpClient) {}public postimage(file: Filedata[]): Observable<Filedata> {return this.http.post<Filedata>('http://localhost:7080/file',file, httpOptions);}}

因为我传回去的是个结构体,里面包含文件名称,文件的base64编码和二进制编码,所以还要定义个结构体,当然标准写法也是要在新建个文件,然后就写这么个结构体。

filedata.ts

export interface Filedata {fileName : stringfileBinary: stringfileBase64: string}

提示

因为上面component.ts文件没有引用,你根据你自己的文件位置去引用(import 。。。。。)service文件和filedata文件

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。