# How to post pictures via API?

**URL:** <https://meta.discourse.org/t/how-to-post-pictures-via-api/314282>\
**Category:** Development\
**Created:** [June 29, 2024, 6:49am UTC](https://meta.discourse.org/t/how-to-post-pictures-via-api/314282 "2024-06-29T06:49:34Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![maxtim](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/maxtim/32/427804_2.png) [@maxtim](https://meta.discourse.org/u/maxtim)\
**Post date:** [June 29, 2024, 6:49am UTC](https://meta.discourse.org/t/how-to-post-pictures-via-api/314282/1 "2024-06-29T06:49:34Z")

</div>

I’ve been working on a [plugin](https://github.com/maxtimbo/discourse-sync) for Obsidian and have been banging my head against the wall trying to get images to upload. This is what I have so far:

```javascript
	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 arrayBuffer = await this.app.vault.readBinary(file);
						const blob = new Blob([arrayBuffer]);
						const boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';
						let body = '';

						body += `--${boundary}\r\n`;
						body += `Content-Disposition: form-data; name="type"\r\n\r\n`;
						body += "composer\r\n";
						body += `--${boundary}\r\n`;
						body += `Content-Disposition: form-data; name="synchronous"\r\n\r\n`;
						body += "true\r\n";

						body += `--${boundary}\r\n`;
						body += `Content-Disposition: form-data; name="files[]"; filename="${file.name}"\r\n`;
						body += `Content-Type: image/jpg\r\n\r\n`
						body += blob + '\r\n';
						body += `--${boundary}--\r\n`;
						console.log(body)
						const formData = new TextEncoder().encode(body)

						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: formData,
							throw: false,
							headers: headers,
						});

						//const response = await fetch(url, {
						//	method: "POST",
						//	body: formData,
						//	headers: new Headers(headers),
						//});

						console.log(`Upload Image response: ${response.status}`);
						//if (response.ok) {
						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)}`);
							//console.error("Error uploading image:", response.status, await response.text());
						}
					} 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;
	}

```

I’m constructing a `multipart/form-data` because [`requestURL()`](https://docs.obsidian.md/Reference/TypeScript+API/request#request()+function) cannot accept a `formData()` as a parameter. Only [`string` or `arrayBuffer`](https://docs.obsidian.md/Reference/TypeScript+API/RequestUrlParam#RequestUrlParam+interface). I cannot use `fetch()` as I get a CORS error. With this code (and many minor tweaks to the `body`) I’m getting the following error:

> Error uploading image: {“errors”:[“You supplied invalid parameters to the request: Discourse::InvalidParameters”],“error\_type”:“invalid\_parameters”}

---

_[View the full topic](https://meta.discourse.org/t/how-to-post-pictures-via-api/314282)._
