Thought I’d go ahead and update as I’m getting a different error massage now:
async uploadImages(imageReferences: string[]): Promise<string[]> {
const imageUrls = [];
for (const ref of imageReferences) {
const filePath = this.app.metadataCache.getFirstLinkpathDest(ref, this.activeFile.name)?.path;
if (filePath) {
const file = this.app.vault.getAbstractFileByPath(filePath) as TFile;
if (file) {
try {
const imgfile = await this.app.vault.readBinary(file);
const boundary = genBoundary();
const sBoundary = '--' + boundary + '\r\n';
let body = '';
body += `${sBoundary}Content-Disposition: form-data; name="type"\r\n\r\ncomposer\r\n`;
body += `${sBoundary}Content-Disposition: form-data; name="synchronous"\r\n\r\ntrue\r\n`;
body += `${sBoundary}Content-Disposition: form-data; name="files[]"; filename="${file.name}"\r\nContent-Type: image/jpg`;
console.log(body);
const eBoundary = '\r\n--' + boundary + '--\r\n';
const bodyArray = new TextEncoder().encode(body);
const endBoundaryArray = new TextEncoder().encode(eBoundary);
const formDataArray = new Uint8Array(bodyArray.length + imgfile.byteLength + endBoundaryArray.length);
formDataArray.set(bodyArray, 0);
formDataArray.set(new Uint8Array(imgfile), bodyArray.length);
formDataArray.set(endBoundaryArray, bodyArray.length + imgfile.byteLength);
const url = `${this.settings.baseUrl}/uploads.json`;
const headers = {
"Api-Key": this.settings.apiKey,
"Api-Username": this.settings.disUser,
"Content-Type": `multipart/form-data; boundary=${boundary}`
};
const response = await requestUrl({
url: url,
method: "POST",
body: formDataArray.buffer,
throw: false,
headers: headers,
});
console.log(`Upload Image response: ${response.status}`);
if (response.status == 200) {
const jsonResponse = response.json();
console.log(`Upload Image jsonResponse: ${JSON.stringify(jsonResponse)}`);
imageUrls.push(jsonResponse.url);
} else {
new NotifyUser(this.app, `Error uploading image: ${response.status}`).open();
console.error(`Error uploading image: ${JSON.stringify(response.json)}`);
}
} catch (error) {
new NotifyUser(this.app, `Exception while uploading image: ${error}`).open();
console.error("Exception while uploading image:", error);
}
} else {
new NotifyUser(this.app, `File not found in vault: ${ref}`).open();
console.error(`File not found in vault: ${ref}`);
}
} else {
new NotifyUser(this.app, `Unable to resolve file path for: ${ref}`).open();
console.error(`Unable to resolve file path for: ${ref}`);
}
}
return imageUrls;
}
The error message I’m receiving now is:
Exception while uploading image: SyntaxError: Unexpected token ‘I’, “Invalid request” is not valid JSON
This is confusing to me because the API states that we need to send a multipart/form-data
, but it’s saying invalid JSON? Maybe it’s related to requestAPI()