Unable to save files in Cloud Functions

Hello,

I’m trying to follow this “https://docs.moralis.io/files#server-side” and save a file in a cloud function.

I’m basically constructing a JSON file and doing some tests, when I call the cloud function it gives me the following error:
Error: File upload by public is disabled.

Here is my full code:

const logger = Moralis.Cloud.getLogger();

Moralis.Cloud.define("saveDataToFile", async (request) => {
  logger.info("saveDataToFile called..."); 
  
  const msg = '{"name":"John", "age":"22"}';
  const jsonObj = JSON.parse(msg);
  const jsonStr = JSON.stringify(jsonObj);

  const data = Array.from(Buffer.from(jsonStr));
  const contentType = "application/json; charset=UTF-8";
  const file = new Moralis.File('datafile1', data, contentType);
  await file.save();

  fileURL = file.url();
  
  logger.info(`fileURL ${fileURL}`);
  
  return {
  	dataUrl: fileURL,
    dataHash: 'hash'
  };
});

Does my account need some special permission to do this?

Thanks,

Hi itheum,

Uploading files requires an authenticated user to prevent spam. In Cloud Code you can get around this with the master key.

await file.save({ useMasterKey: true })
1 Like

Thanks for that! Makes sense…

@mayjer Hi! And how would be possible to get the hash value of the file? Thanks in advance

Hi @pedrosantos,

To retrieve the hash value of the file once uploaded on IPFS, you can check out the code over here -https://docs.moralis.io/ipfs#getting-files

Hope this helps. :slight_smile:

Hi @malik Thanks, but I am still struggling. Is the code from this post saving the file on IPFS or only on Moralis server? I would like to save a file in the IPFS, how can I do it from a cloud function?

Hi @pedrosantos,

This is the code to save on IPFS. Doing it in cloud function works the same way but it’s more advisable to upload files from your front end.

Code give in the docs –

// Save file input to IPFS
const data = fileInput.files[0]
const file = new Moralis.File(data.name, data)
await file.saveIPFS();

//console.log(file.ipfs(), file.hash())

// Save file reference (which was uploaded to IPFS) to Moralis
const jobApplication = new Moralis.Object('Applications')
jobApplication.set('name', 'Satoshi')
jobApplication.set('resume', file)
await jobApplication.save()

// Retrieve file
const query = new Moralis.Query('Applications')
query.equalTo('name', 'Satoshi')
query.find().then(function ([application]) {
   const ipfs = application.get('resume').ipfs()
   const hash = application.get('resume').hash()
   console.log('IPFS url', ipfs)
   console.log('IPFS hash', hash)
})

Hi @malik,

I already tried that, however, I am getting always the error “file.saveIPFS is not a function”.

(I had it in the client side, however in this case, I can’t trust the client, so I need to do it from the cloudfunction.)
Thanks