|
| 1 | +import { IBasicRequestService } from '@/service/common/request'; |
| 2 | +import { RequestHelper } from '@/service/request/common/request'; |
| 3 | +import { UploadImageRequest, ImageHostingService } from '../interface'; |
| 4 | +import { Base64ImageToBlob } from '@/common/blob'; |
| 5 | +import Container from 'typedi'; |
| 6 | +import md5 from '@web-clipper/shared/lib/md5'; |
| 7 | + |
| 8 | +export interface PiclistImageHostingOption { |
| 9 | + uploadUrl: string; |
| 10 | + key: string; |
| 11 | +} |
| 12 | + |
| 13 | +export default class PiclistImageHostingService implements ImageHostingService { |
| 14 | + private config: PiclistImageHostingOption; |
| 15 | + |
| 16 | + constructor(config: PiclistImageHostingOption) { |
| 17 | + this.config = config; |
| 18 | + } |
| 19 | + |
| 20 | + getId = () => { |
| 21 | + let uploadUrl = this.config.uploadUrl |
| 22 | + if(this.config.key) |
| 23 | + uploadUrl += `?key=${this.config.key}` |
| 24 | + return md5(uploadUrl) // as id |
| 25 | + }; |
| 26 | + |
| 27 | + uploadImage = async ({ data }: UploadImageRequest) => { |
| 28 | + const blob = Base64ImageToBlob(data); |
| 29 | + return this.uploadBlob(blob); |
| 30 | + }; |
| 31 | + |
| 32 | + uploadImageUrl = async (url: string) => { |
| 33 | + const imageBlob = await Container.get(IBasicRequestService).download(url); |
| 34 | + return this.uploadBlob(imageBlob); |
| 35 | + }; |
| 36 | + |
| 37 | + private uploadBlob = async (blob: Blob): Promise<string> => { |
| 38 | + const request = new RequestHelper({ request: Container.get(IBasicRequestService) }); |
| 39 | + let uploadUrl = this.config.uploadUrl |
| 40 | + if(this.config.key) |
| 41 | + uploadUrl += `?key=${this.config.key}` |
| 42 | + let formData = new FormData(); |
| 43 | + formData.append('image', blob); |
| 44 | + let result = await request.postForm<{ success: boolean, result: string[] }>( |
| 45 | + uploadUrl, |
| 46 | + { |
| 47 | + data: formData, |
| 48 | + } |
| 49 | + ); |
| 50 | + if(!result.success) |
| 51 | + throw new Error("Upload failed"); |
| 52 | + return result.result[0]; |
| 53 | + }; |
| 54 | +} |
0 commit comments