-
Hi! I'm trying to upload listing images from a node.js app using node-fetch, but getting export async function uploadListingImage(
shopId: number,
listingId: number,
oauthToken: string,
apiKey: string,
rank: number,
imageFilePath: string,
): Promise<any> {
const url = etsyUploadListingImageUrl(shopId, listingId);
const fileContent = fs.readFileSync(imageFilePath, { encoding: "binary" });
const headers = new Headers();
headers.set("Authorization", `Bearer ${oauthToken}`);
headers.set("x-api-key", apiKey);
const body = new FormData();
body.set("rank", rank.toString());
body.append("image", new Blob([fileContent]), "image.jpg");
let res;
try {
res = await fetch(url, {
method: "POST",
headers,
body,
});
} catch (error) {
console.error("error uploading listing image", { error });
throw error;
}
return res?.json();
} Thank you very much for any help. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I also tried using |
Beta Was this translation helpful? Give feedback.
-
I think I figured it out. I hadn't explicitly imported This code works: import fs from "fs";
import path from "path";
import fetch from "node-fetch";
import FormData from "form-data";
const API_URL = "https://openapi.etsy.com/v3/application";
function etsyUploadListingImageUrl(shopId: number, listingId: number) {
return `${API_URL}/shops/${shopId}/listings/${listingId}/images`;
}
export async function uploadListingImage(
shopId: number,
listingId: number,
oauthToken: string,
apiKey: string,
rank: number,
imageFilePath: string,
): Promise<any> {
const url = etsyUploadListingImageUrl(shopId, listingId);
const headers = new Headers();
headers.set("Authorization", `Bearer ${oauthToken}`);
headers.set("x-api-key", apiKey);
const body = new FormData();
body.append("rank", rank.toString());
body.append("image", fs.createReadStream(imageFilePath), {
contentType: "image/jpeg",
filename: path.basename(imageFilePath),
});
let res;
try {
res = await fetch(url, {
method: "POST",
headers,
body,
});
} catch (error) {
console.error("error uploading listing image", { error });
throw error;
}
return res?.json();
} |
Beta Was this translation helpful? Give feedback.
I think I figured it out. I hadn't explicitly imported
FormData
and it looks like maybe Next.js implementation/polyfill doesn't support files? IDKFCThis code works: