Last active
March 17, 2021 09:25
-
-
Save RomanRobot/5df39ceef64ebda04278a0e4faee3f96 to your computer and use it in GitHub Desktop.
Synology FileStation Upload function (TypeScript, Angular, Capacitor, Filesystem, Ionic, FormData, HttpClient)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { HttpClient } from '@angular/common/http'; | |
type Response<T> = { | |
data: T; | |
success: boolean; | |
error: {code: number, errors: []}; | |
} | |
type API = { | |
name: string, | |
version: number, | |
path: string, | |
supported: boolean | |
}; | |
export enum ExistingFileAction { | |
Overwrite, | |
Skip, | |
ErrorResponse | |
} | |
private fsUploadAPI: API = { name: 'SYNO.FileStation.Upload', version: 2, path: undefined, supported: false }; | |
public async upload(fileContent: string, fileName: string, destinationFolder: string, createParents: boolean, existingFileAction: ExistingFileAction) { | |
if (this.sessionId === undefined) { | |
console.error('Can\'t upload files. Not logged in.'); | |
return; | |
} | |
let formData = new FormData(); | |
formData.append('api', this.fsUploadAPI.name); | |
formData.append('version', this.fsUploadAPI.version.toString()); | |
formData.append('method', 'upload'); | |
formData.append('path', destinationFolder); // NOTE: destinationFolder has leading slash and no trailing slash. | |
formData.append('create_parents', createParents.toString()); | |
let overwrite; | |
switch (existingFileAction) | |
{ | |
case ExistingFileAction.Overwrite: | |
overwrite = true; | |
break; | |
case ExistingFileAction.Skip: | |
overwrite = false; | |
break; | |
case ExistingFileAction.ErrorResponse: | |
// Exclude 'overwrite' argument for error response. | |
break; | |
} | |
if (overwrite !== undefined) { | |
formData.append('overwrite', overwrite); | |
} | |
formData.append('_sid', this.sessionId); | |
formData.append('file', new Blob([fileContent]), fileName); | |
let url = `https://insert.your.synology.drive.ip.here:5001/webapi/${this.fsUploadAPI.path}`; | |
console.log('POST ' + url); | |
return this.http.post<Response<any>>(url, formData).toPromise(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment