How to upload file in website page with a normal HTML form ?
On the template:
<template id="upload">
<form action="process" method="POST" enctype="multipart/form-data" >
Upload file:
<input type="file" name="attachment"/>
<button string="upload" type="submit" name="submit">Upload</button>
</form>
</template>
On the controller
# -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request
import base64
class VitUpload(http.Controller):
@http.route('/vit_upload/upload', auth='public')
def upload(self, **kw):
return http.request.render('vit_upload.upload', {})
@http.route('/vit_upload/process', auth='public', method="POST", csrf=False)
def process(self, **post):
if post.get('attachment', False):
name = post.get('attachment').filename
file = post.get('attachment')
attachment = file.read()
encoded = base64.b64encode(attachment)
print(encoded)
return "upload process success"
Main things:
The html form must have enctype="multipart/form-data"
The processing handler must encode the uploaded file content to base64 encoded string, then save the string to attachment or a field with type binary on a model.
Example:
payment = request.env['account.payment'].browse(payment_id)
payment.attachment = encoded