Home > database >  How to use Resmush.it API from Apps Script (multi files upload)
How to use Resmush.it API from Apps Script (multi files upload)

Time:06-01

I'm trying to use the resmush.it API from Apps Script and I'm struggling when making the request with UrlFetch.

From their documentation, I understand they need a files array, in a multipart/form-data request.

What I'm doing so far (the images come from a Google Slides)

function myFunction() {
  const OPTIMIZER_URL = "http://api.resmush.it/ws.php"
  let slides = SlidesApp.openById("1TUZSgG_XXX_ni6VhdbE5usRyMc");
  let pages = slides.getSlides();
  pages.forEach((page) => {
    let images = page.getImages();
    images.forEach(image => {
        let payload = {
          files: [{
            file: image.getBlob()
          }]
        }
        let options = {
          method: "POST",
          payload: payload,
          muteHttpExceptions : true
        }
        let response = UrlFetchApp.fetch(OPTIMIZER_URL, options)
        let jsonResponse = JSON.parse(response.getContentText())
        console.log(jsonResponse);
    })
  })
}

I also tried with payload = { file: image.getBlob() } but no success.

I get this error everytime:

{ error: 400,
  error_long: 'No file or url provided',
  generator: 'reSmush.it rev.3.0.4.20210124' }

Can you see what is wrong ?

Thank you

CodePudding user response:

Although I'm not sure whether from your provided document I could correctly understand the specification of the API you want to use, how about the following modified script?

When I saw your script, I'm worried that your image.getBlob() has no name. In that case, the data is not sent as files. I thought that this might be the reason for your issue. When my this guess is reflected in your script, it becomes as follows.

Modified script:

function myFunction() {
  const OPTIMIZER_URL = "http://api.resmush.it/ws.php"
  let slides = SlidesApp.openById("1TUZSgG_XXX_ni6VhdbE5usRyMc");
  let pages = slides.getSlides();
  pages.forEach((page) => {
    let images = page.getImages();
    images.forEach(image => {
      let options = {
        method: "POST",
        payload: { files: image.getBlob().setName("sample") },
        muteHttpExceptions: true
      }
      let response = UrlFetchApp.fetch(OPTIMIZER_URL, options)
      console.log(response.getContentText());
    })
  })
}
  • In this modification, the request body uses { files: image.getBlob().setName("sample") }. I'm not sure about the detailed specification of the API you want to use. So, if the key of files cannot be used, please modify files to file and test it again.

  • And, if your API is required to use the unique names of the uploaded files for each request, please set the unique names by modifying sample of image.getBlob().setName("sample").

Reference:

  • Related