Fetch/XHR File upload

Hi,
currently working on plugin using new UXP api for Photoshop. My goal is to export the current visible file as a single PNG file, then grab this file and send it to backend.

I was able to export file using:

const uxp = require('uxp');
const PS = require('photoshop');
const lfs = uxp.storage.localFileSystem;
const activeDoc = PS.app.activeDocument;

async function exportFile() {
  let tempFolder = await lfs.getTemporaryFolder();
  await activeDoc.save(await tempFolder.createFile('temp.png'));

  setTimeout(async function () {
    const tempFile = (await tempFolder.getEntries()).find(entry => entry.name === 'temp.png');
    const data = await tempFile.read({ format: uxp.storage.formats.binary });
   //uploadXHR(data)
   //uploadFetch(data)
  }, 2000)
}

And now I’m having problems sending this file to backend. In CEP I’ve used to use node.js for grabing file and sending it to backend.

But now we dont have node.js so I’ve tried fetch and XHR and I have weird errors. Can someone help?

My XHR:

const uploadXHR = (file) => {
  const API_URL = 'http://localhost:8070'
  const UPLOAD_ENDPOINT = `${API_URL}/api/upload`;

  const xhr = new XMLHttpRequest();
  xhr.onload = () => {
    console.log(xhr.status)
  };

  xhr.onerror = (e) => {
    reject(new TypeError('Network request failed'));
  };

  xhr.ontimeout = () => {
    reject(new TypeError('Network request failed'));
  };

  xhr.open('POST', UPLOAD_ENDPOINT);
  xhr.send(file);
}

and my fetch:

const uploadFetch = (file) => {
  const API_URL = 'http://localhost:8070'
  const UPLOAD_ENDPOINT = `${API_URL}/api/recognition/async`;
  var data = new FormData()
  data.append('image', file)
  let response = await fetch(UPLOAD_ENDPOINT, {
    method: 'post',
    body: data
  });

  if (!response.ok) {
    throw new Error(`HTTP error fetching weather station; status: ${response.status}`);
  }

  let resJson = await response.json();
  console.log(resJson)
} 

What error(s) are you getting?

Also, try http://127.0.0.1:8070 and see if that does any better.

Request are not reaching my server. Changing from localhost to http://127.0.0.1:8070 resolved my issue.

Cool. localhost is subject to any local security restrictions like App Transport Security and the like, where as 127.0.0.1 is usually excluded. (Don’t know why, but thankfully one of those is!)

3 Likes