# Télécharger un fichier à partir d'une URL

La méthode suivante permet de télécharger un fichier depuis une URL, de le convertir en base64, puis (optionnellement) de l’écrire directement dans un champ d’un enregistrement Open-Prod. Cela peut servir par exemple dans une action serveur pour alimenter une pièce jointe à partir d’un lien externe.

<table border="1" id="bkmrk-m%C3%A9thode-%2F-exemple-do" style="width: 100%; height: 424.8px;"><tbody><tr style="background-color: rgb(236, 240, 241); height: 29.6px;"><td style="width: 34%; height: 29.6px;">**Méthode / Exemple**</td><td style="width: 33%; height: 29.6px;">**Données d'entrée**</td><td style="width: 33%; height: 29.6px;">**Données de sortie**</td></tr><tr style="height: 281.6px;"><td style="width: 34%; height: 281.6px;">**mf\_downloadfile\_to\_field(url, recordset=False, field=False)**

</td><td style="width: 33%; height: 281.6px;">**Paramètres :**

\- **url** (str, obligatoire) : URL du fichier à télécharger

\- **recordset** (Model, optionnel) : enregistrement cible

\- **field** (str, optionnel) : nom du champ à écrire

**Règles :**

\- fournir les 2 paramètres recordset + field, ou aucun des deux

\- extensions bloquées : .exe, .dll, .msi, .bat, .cmd, .ps1, .sh, .js, .jar, .vbs, svg, html, htm, xhtml, xml

\- timeout de téléchargement : 30 secondes

\- taille maxi fichier 10 mo

</td><td style="width: 33%; height: 281.6px;">\- retourne le contenu du fichier encodé en base64 (bytes)

\- si recordset + field sont fournis : écriture automatique dans le champ ciblé

\- contrôles inclus : URL vide, paramètres incohérents, recordset invalide, enregistrement inexistant, champ inconnu, type de fichier dangereux, erreur de téléchargement

</td></tr><tr style="height: 113.6px;"><td style="height: 113.6px;">**Comportement en erreur**</td><td style="height: 113.6px;">Cas typiques :

\- URL absente

\- recordset sans field (ou l'inverse)

\- extension ou contenu interdite

\- URL inaccessible / erreur HTTP / timeout

\- field absent du modèle cible

</td><td style="height: 113.6px;">La méthode lève une ValidationError (ou Warning pour extension dangereuse).

</td></tr></tbody></table>

  
Exemple : dans une action serveur

```python
Exemple 1 :

url = "https://www.1life.fr/wp-content/uploads/2023/12/1Life-LOGO.png"
target_records = env['product.product'].browse(2)
env['mf.tools'].mf_downloadfile_to_field(url, target_records, 'picture')

Exemple 2 :

url = "https://www.1life.fr/wp-content/uploads/2023/12/1Life-LOGO.png"
target_records = env['product.product'].browse(2)
image=env['mf.tools'].mf_downloadfile_to_field(url)
target_records.write({'picture':image})
```

**Remarque :** le champ cible doit exister sur le modèle et être adapté au stockage d’un contenu base64 (généralement un champ binaire).