Import et sauvegarde d'un fichier via un Custom Widget Builder / upload - charger PJ depuis custom widget

ça y est ça marcheeeee :partying_face:

@florent.fayolle a trouvé pourquoi mon code d’upload de PJ ne marchait pas, il manquait l’en-tête "X-Requested-With": "XMLHttpRequest" !
noctule

Voici les étapes pour faire l’upload/chargement d’une PJ dans une table :

  • Récupérer le token
    const tokenInfo = await grist.docApi.getAccessToken({ readOnly: false });

  • Faire la requête API de chargement du fichier (pour le stocker mais il n’est pour l’instant pas lié à une table)

const formData = new FormData();
formData.append('upload', file, file.name);

const response = await fetch(`${tokenInfo.baseUrl}/attachments?auth=${tokenInfo.token}`, {
		method: 'POST',
		body: formData,
		headers: {
          		"X-Requested-With": "XMLHttpRequest",
    				},
});
  • Récupérer les PJs existantes de la cellule
    const existingAttachments = currentRecord.PJ || [];

  • Créer la liste incluant la nouvelle PJ

const newAttachmentsList = Array.isArray(existingAttachments) 
						? [...existingAttachments, attachmentId]
						: [attachmentId];
  • Mettre à jour la cellule avec la nouvelle PJ

const table = await grist.getTable();

await table.update({
	d: currentRecord.id,
	fields: {
	PJ: ['L', ...newAttachmentsList]
	      }
	});

Doc d’exemple avec le custom widget : Ex - envoyer un email avec PJ - Grist

Le code complet ci-dessous :

<!doctype html>
<html lang="fr">
	<head>
		<meta charset="utf-8"/>
		<script src="https://docs.getgrist.com/grist-plugin-api.js"></script>
		<style>
			body {
				font-family: system-ui;
				padding: 20px;
			}
			button, input {
				margin-top: 8px;
			}
			pre {
				background: #f6f8fa;
				padding: 8px;
				border-radius: 6px;
				white-space: pre-wrap;
			}
		</style>
	</head>
	<body>
		<h3>📎 Uploader une PJ</h3>
		<input type="file" id="fileInput" />
		<button id="uploadBtn">Uploader</button>
		<pre id="log">En attente...</pre>

		<script>
			const log = document.getElementById('log');
			const fileInput = document.getElementById('fileInput');
			const uploadBtn = document.getElementById('uploadBtn');

			let currentRecord = null;
			let tableId = null;

			// Initialiser Grist
			grist.ready({ requiredAccess: 'full', columns: [{ name: 'Attachments', type: 'Attachments' }] });

			// Récupérer la ligne sélectionnée
			grist.onRecord((record, mappings) => {
				currentRecord = record;
				log.textContent = `Ligne sélectionnée: id=${record.id}`;
			});

			console.log("uploadBtn", uploadBtn);
			uploadBtn.addEventListener('click', async () => {
		
				const file = fileInput.files[0];

				if (!file) {
					log.textContent = '❌ Sélectionne un fichier';
					return;
				}
				
				if (!currentRecord) {
					log.textContent = '❌ Sélectionne une ligne dans Grist';
					return;
				}

				try {
					log.textContent = '⏳ Upload en cours...';

					// 1. Récupérer un access token (avec droits d'écriture)
					const tokenInfo = await grist.docApi.getAccessToken({ readOnly: false });
					log.textContent += `\n✅ Token obtenu`;

					// 2. Uploader le fichier via l'API REST
					const formData = new FormData();
					formData.append('upload', file, file.name);

					const response = await fetch(`${tokenInfo.baseUrl}/attachments?auth=${tokenInfo.token}`, {
						method: 'POST',
						body: formData,
						headers: {
          		"X-Requested-With": "XMLHttpRequest",
    				},
					});

					if (!response.ok) {
						throw new Error(`Upload échoué: ${response.status} ${response.statusText}`);
					}

					const result = await response.json();
					const attachmentId = result[0];
					log.textContent += `\n✅ Fichier uploadé, id=${attachmentId}`;

					// 3. Récupérer les PJs existantes de la cellule
					const existingAttachments = currentRecord.PJ || [];
					// Grist stocke les attachments sous forme ['L', id1, id2, ...]
					// Mais onRecord les renvoie déjà décodés en array
					const newAttachmentsList = Array.isArray(existingAttachments) 
						? [...existingAttachments, attachmentId]
						: [attachmentId];

					// 4. Mettre à jour la cellule avec la nouvelle PJ
					const table = await grist.getTable();
					await table.update({
						id: currentRecord.id,
						fields: {
							PJ: ['L', ...newAttachmentsList]
						}
					});

					log.textContent += `\n✅ Attachment lié à la ligne ${currentRecord.id}`;
					log.textContent += `\n\n🎉 Terminé !`;

				} catch (err) {
					log.textContent += `\n❌ Erreur: ${err.message}`;
					console.error(err);
				}
			});
		</script>
	</body>
</html>
1 « J'aime »