0

In my mutation I need to upload a file to an Asset Field. Can this all be done in one mutation or do you need to upload the file in one mutation and assign the id to the asset field in a secondary mutation?

mutation($document:FileInput) {
   save_sectionHandle_entryType_Entry(document:$document) {
      document {
          id
          title
          url
      }
   }
}

// Params
{
    document: { fileData: Base64 file data, filename: String }
}
1
  • have you ever found a solution to this?
    – obs
    Jul 15, 2022 at 10:05

1 Answer 1

0

I have found a solution to using GQL to upload a file for an Entry's Asset Field.

  1. Create file input field & process adding file.
  2. When file is added to file input field, save the asset to the assets volume using:
export const SET_DOCUMENTS_ASSET = gql`
  mutation($document: FileInput) {
    save_documents_Asset(_file: $document, newFolderId: 5) {
      id
      filename
      title
    }
  }
`;

/* 
  FileInput is expecting an object as { fileName:"", id:NaN }
  When saving file for first time leave id:NaN when resaving pass asset id
*/
  1. On SET_DOCUMENTS_ASSET promise grab the returned ID of the Asset.
  2. When saving the Form use that asset(s) ID(s) to set the Entry's Asset(s)
export const SET_ENTRY = gql`
  mutation (
    $document: [Int]
  ) {
    save_section_entrytype_Entry(
      document: $document
    ) {
      id
      title
      document {
        id
        url
        title
      }
    }
  }
`;

If the user needs to select a different file, here are steps too removed saved asset.

  1. Allow user to remove file from the File Input.
  2. On removal of file delete the asset from the Volume passing the ID of the asset you originally saved:
export const DELETE_ASSET = gql`
  mutation($id: Int!){
    deleteAsset(id:$id)
  }
`;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.