WP-API / node-wpapi

An isomorphic JavaScript client for the WordPress REST API
http://wp-api.org/node-wpapi/
MIT License
1.68k stars 191 forks source link

Unable to Upload Buffer Media File (Type Errors) #514

Open jimburch opened 10 months ago

jimburch commented 10 months ago

I'm running wpapi in an express server and want to upload a Buffer from Express.Multer.File data. The docs say the file() method can accept a Buffer when added I get the error: Argument of type 'Buffer' is not assignable to parameter of type 'string | File'. Type 'Buffer' is missing the following properties from type 'File': lastModified, name, webkitRelativePath, size, and 4 more.ts(2345

Here is my setup:

image image

I'm console logged buffer to make sure it is in fact a Buffer and I get buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 43 00 03 02 02 03 02 02 03 03 03 03 04 03 03 04 05 08 05 05 04 04 05 0a 07 07 06 ... 70963 more bytes>,

dinhmai74 commented 6 months ago

I ended up to do send fetch request myselft and it solved the problem

  const title = params.title;
    const fd = new FormData();
    fd.append("title", title);
    fd.append("caption", title);
    fd.append("alt_text", title);
    fd.append("description", title);
    fd.append("file", new Blob([buffer]), filename);

    const headers = new Headers();
    headers.append(
      "Content-Disposition",
      'attachment; filename="' + "files.jpeg" + '"',
    );
    const auth = `Basic ${Buffer.from(username + ":" + password).toString(
    "base64",
   )}`;
    headers.append("Authorization", auth);
    const response = await fetch(`https://${project.url}/wp-json/wp/v2/media`, {
      method: "POST",
      headers,
      body: fd,
    });

    const media = (await response.json()) as WpMedia;

    return media;