|
import { createReadStream } from "fs"; |
|
import { Observable } from "rxjs"; |
|
import { map } from "rxjs/operators"; |
|
import Axios from "axios-observable"; |
|
import FormData from "form-data"; |
|
|
|
const startingArgumentIndex = 2; |
|
if (process.argv[startingArgumentIndex] === "--help") { |
|
console.log( |
|
`usage: npm run start -- baseURL token project_id table_id pathToImage` |
|
); |
|
process.exit(1); |
|
} |
|
const [baseURL, token, project_id, table_id, imagePath]: string[] = process.argv.slice(startingArgumentIndex); |
|
|
|
interface photoMetaResponse { |
|
url: string; |
|
title: string; |
|
mimetype: string; |
|
size: number; |
|
} |
|
|
|
/** |
|
* @param imagePath ex: "C:/Users/BABAR/Pictures/MyPicture.jpeg" |
|
* @param authToken token optained from `copy auth Token`. |
|
* @param baseURL name of your nocodb server |
|
* @param project_id extracti if from swagger api example |
|
* @returns |
|
*/ |
|
function uploadImage(imagePath: string, authToken: string, baseURL: string, project_id: string): Observable<photoMetaResponse> { |
|
const jsonParam = JSON.stringify({ "api" : "xcAttachmentUpload", project_id, "dbAlias" : "db", "args" : {}}); |
|
const formData = new FormData(); |
|
formData.append("file", createReadStream(imagePath)); |
|
formData.append("json", jsonParam); |
|
return Axios.request<photoMetaResponse>({ |
|
url: `${baseURL}/dashboard`, |
|
data: formData, |
|
headers: { |
|
"Content-Type": `multipart/form-data; boundary=${formData.getBoundary()}`, // the important part |
|
"xc-auth": authToken |
|
}, |
|
method: "post", |
|
params: { project_id } |
|
}).pipe( |
|
map(x => x.data) |
|
); |
|
} |
|
|
|
uploadImage(imagePath, token, baseURL, project_id) |
|
.pipe( |
|
map(v => JSON.stringify([v])), |
|
) |
|
.subscribe({next: pic => { |
|
Axios.request<unknown>({ |
|
url: `${baseURL}/nc/${project_id}/api/v1/${table_id}`, |
|
data: { |
|
"title": "my Picture !", |
|
picColumn: pic // change here to uppload a new row with correct header. picColumn must be of type "attachement" |
|
}, |
|
headers: { |
|
"Content-Type": "application/json", |
|
"xc-auth": token |
|
}, |
|
method: "post", |
|
params: { project_id } |
|
}).subscribe(); |
|
}, |
|
error: console.error |
|
}); |
Hey - I get a ts compile error but don't know any ts and can't debug. This is my log:
Cheers