Enable Dark Mode!
how-to-add-attachments-to-website-form-using-js-in-odoo-17.jpg
By: Muhsina V

How to Add Attachments to Website Form Using JS in Odoo 17

Technical

On the Odoo website, users can fill out various forms to provide information. These forms can include an input field for uploading files.

Here’s how to configure such an input field:

* The <input> element with the type="file" attribute specifies the field for file uploads.

* The multiple="true" attribute allows users to select multiple files at once.

* The accept="image/*, application/pdf, video/*" attribute restricts the selectable file types to images, PDFs, and videos.

* The required="1" attribute ensures that users must select a file before submitting the form.

The form also includes a submit button (<button type="submit">Upload</button>) to trigger the submission. When the form is submitted, the selected files are sent to the server via an HTTP POST request, enabling Odoo to handle the file uploads accordingly.

Let's create a web form now with a file input area.

<div class="upload_form form-group">
    <div class="col-lg-3 col-md-4 text-right">
       <label class="col-form-label"
              for="attachment">Attachment
       </label>
    </div>
    <div class="col-lg-7 col-md-8">
       <input class="file" id="attachments" type="file" name="attachments" multiple="true" accept="image/*,application/pdf,video/*" required="True"/>
    </div>
</div>

The following image shows how the web form for uploading files looks.

How to Add Attachments to Website Form Using JS in Odoo 17-cybrosys

We've added a file upload field to the web form. When a user selects a file (triggers the 'change' event), a JavaScript function will be called to capture the file data.

/** @odoo-module */

import publicWidget from '@web/legacy/js/public/public_widget';
import { jsonrpc } from "@web/core/network/rpc_service";
publicWidget.registry.form = publicWidget.Widget.extend({
    selector: '.upload_form',
    events: {
        'change #file_input': 'attachment_upload',
    },
    attachment_upload: function(e) {
        var attachments = e.target.files;
        for (let i = 0; i < attachments.length; i++) {
            var reader = new FileReader();
            reader.readAsDataURL(attachments[i]);
            reader.onload = function(e) {
                jsonrpc('/upload_attachment', {
                    'attachments': e.target.result,
                    'attachment_name': attachments[i].name
                });
            }
        }
    },
});

When the user selects files, a JavaScript function creates a list named attachments

to store the information for each uploaded file. Since the form allows multiple file uploads, this list will contain multiple objects. We can then iterate through this list using a for loop to access the data of each individual file and save it to the ir.attachments model in Odoo.

When a user selects files, we can access information like file names, types, and sizes. This information can then be used to store the files in the database.

We create a variable called reader and assign it the result of the FileReader() function.

The FileReader object allows us to asynchronously read the contents of the selected file. We can define a function to handle the onload event of the reader. This event fires when the file content is available after using methods like readAsArrayBuffer, readAsBinaryString, readAsDataURL, or readAsText.

Once the file is fully loaded (load event handler), the JavaScript code extracts the base64-encoded data representing the file contents. This data, along with the original file name, is then sent to a Python function on the server for further processing.

  from odoo.http import Controller, route, request
import base64


class WebsiteFormAttachment(Controller):
    
    @route('/upload_attachment', type='json', auth="public", methods=['POST'], website=True)
    def upload_attachment(self, **kw):
        base64_data = kw['attachments'].split(",")[1]
        Attachments = request.env['ir.attachment']
        Attachments.sudo().create({
            'name': kw['attachment_name'],
            'type': 'binary',
            'datas': base64.b64decode(base64_data),
        })
        return {'status': 'success'}

Here, the upload_attachment function receives base64-encoded file data and the file name from the client-side JavaScript. It extracts the actual binary data (base64_data) by stripping the header (data:application/pdf;base64,). This data is then stored in Odoo's ir.attachment model, which manages file attachments.

By integrating this setup, users can seamlessly upload files via web forms on your Odoo website, enhancing interactivity and functionality.

To read more about How to Add Attachments in Website Form Using JS in Odoo 16?, refer to our blog How to Add Attachments in Website Form Using JS in Odoo 16?.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message