Skip to Content
Menu
This question has been flagged
2 Replies
3481 Views

How can we download a static file (we will put it in /static/files folder) from menu action?

Avatar
Discard
Author Best Answer

I have solved problem... Thanks for your code

1. Menu Action

2. Action 

Download Filefield>ir.actions.serverfield>codefield> action = model.get_stock_file()field>record>

3. Function to download

def get_stock_file(self):  url = str('/ox_fee/static/files/OurSampleFile.xlsx')
return {'type' : 'ir.actions.act_url','url': url,'target': 'self' }



Avatar
Discard
Best Answer

follow this way:

  1. Create a new Python controller:
from odoo import http
from odoo.http import request
import os


class FileDownloadController(http.Controller):
 
@http.route('/file/download', type='http', auth='user')
def file_download(self):
file_path = '/static/files/your_file.txt' # Update with the actual file path
 
# Get the absolute path of the file
full_path = os.path.join(request.env['ir.config_parameter'].get_param('web.base.url'), file_path)
 
# Read the file and return it as a response
with open(full_path, 'rb') as file:
file_data = file.read()
 
# Set the response headers for file download
response = request.make_response(file_data)
response.headers['Content-Disposition'] = 'attachment; filename="your_file.txt"' # Update with the desired file name
response.mimetype = 'application/octet-stream'
 
return response

  1. Create a menu action that triggers the file download:

field name="name">Download File/field>
field name="type">ir.actions.server/field>
field name="model_id" ref="model_your_model"/>
field name="state">code/field>
field name="code">
action = self.env["ir.actions.act_url"].sudo().with_context(
action_id=self.id, dialog=True).create({
"name": "File Download",
"url": "/file/download",
"target": "new",
})
return {"action": action}
/field>
/record>

  1. Add the menu action to the desired menu:
menuitem id="menu_item_file_download" name="Download File" action="menu_action_file_download"/>

With this setup, when the user selects the "Download File" menu item, the file will be downloaded through the custom controller's file_download method.


note: here i remove the XML tag like(< >) because when i edit the tag and save the answer the i didn't see the full code of XML,so please add the (<>) once you edit the XML file

Avatar
Discard
Author

Thanks.. Let me try..

Related Posts Replies Views Activity
1
May 20
6683
1
Jan 23
5485
0
Jan 22
2074
0
Jan 24
1035
6
Jun 24
5755