aboutsummaryrefslogtreecommitdiff
path: root/src/lib/image.ts
blob: 6ab20a553fc2c5f1dd6a251da22fc6357296c29f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { api } from './api';
import { v4 as uuidV4 } from 'uuid';
import { writeFileSync } from 'fs';

export async function getImg(imgId: string) {
  if(imgId == null || imgId == '' || imgId == undefined) return null;

  const response = await api('get', `image/${imgId}`)

  if(response.status !== 200) return `Server error: ${response.status}`;
  return response.text();
}

export async function postImg(img: string) {
  if(!img) return null;

  img = img.split(':')[1];        // remove 'data:' part
  let img_b64= img.split(',')[1]; // remove header
  let fileExt = img.split(',')[0].split('/')[1].split(';')[0];
  let filename = `${uuidV4()}.${fileExt}`;

  //save file in this server
  // writeFileSync(`dist/client/images/${filename}`, img_b64, "base64");
  writeFileSync(`public/images/${filename}`, img_b64, "base64");

  let data = {
    'name': filename,
    'base64': img_b64
  };
  await api('post', 'image', JSON.stringify(data));

  return filename;
}

export function getImgType(img: string): string
{
  if(!img) return null;
  return img.split('/')[0].split(':')[1];
}