first-api & file-upload

This commit is contained in:
King Wang
2021-06-09 22:38:55 +08:00
parent 6c0c206b05
commit 1e3bfeb987
37 changed files with 491 additions and 3 deletions

View File

@@ -0,0 +1,46 @@
import { HttpClient } from 'tsrpc-browser';
import { serviceProto } from './shared/protocols/serviceProto';
let client = new HttpClient(serviceProto, {
server: 'http://127.0.0.1:3000',
logger: console
});
async function upload() {
// Load File
let file = document.querySelector('input[type=file]') as HTMLInputElement;
if (!file.files || !file.files[0]) {
alert('Please select a file')
return;
}
let fileData = await loadFile(file.files[0]);
// Upload
let ret = await client.callApi('Upload', {
fileData: fileData,
fileName: file.files[0].name
});
// Error
if (!ret.isSucc) {
alert(ret.err.message);
return;
}
// Succ
document.querySelector('ol')!.innerHTML += `<li><a href="${ret.res.url}" target="_blank">${ret.res.url}</a></li>\n`;
file.value = '';
alert('Upload successfully!')
}
function loadFile(file: File): Promise<Uint8Array> {
return new Promise(rs => {
let reader = new FileReader();
reader.onload = e => {
rs(new Uint8Array(e.target!.result as ArrayBuffer))
}
reader.readAsArrayBuffer(file);
})
}
document.querySelector('button')!.onclick = upload;

View File

@@ -0,0 +1,8 @@
export interface ReqUpload {
fileName: string,
fileData: Uint8Array
}
export interface ResUpload {
url: string;
}

View File

@@ -0,0 +1,59 @@
import { ServiceProto } from 'tsrpc-proto';
import { ReqUpload, ResUpload } from './PtlUpload';
export interface ServiceType {
api: {
"Upload": {
req: ReqUpload,
res: ResUpload
}
},
msg: {
}
}
export const serviceProto: ServiceProto<ServiceType> = {
"version": 2,
"services": [
{
"id": 0,
"name": "Upload",
"type": "api"
}
],
"types": {
"PtlUpload/ReqUpload": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "fileName",
"type": {
"type": "String"
}
},
{
"id": 1,
"name": "fileData",
"type": {
"type": "Buffer",
"arrayType": "Uint8Array"
}
}
]
},
"PtlUpload/ResUpload": {
"type": "Interface",
"properties": [
{
"id": 2,
"name": "url",
"type": {
"type": "String"
}
}
]
}
}
};