简体   繁体   English

如何Web2py自定义下载功能

[英]How to Web2py custom download function

I'm developing a simple webapp in web2py and I want to create a link that let's the user download a file. 我正在web2py中开发一个简单的webapp,我想创建一个让用户下载文件的链接。 Like this: 像这样:

<a href="{{=URL('download',args = FILE)}}" download>

However, I want to do this without having to pass the FILE to the user in the page handler. 但是,我想在不必将页面处理程序中的FILE传递给用户的情况下执行此操作。 I want to retrieve an ID from the server asynchronously that will correspond to the file I want to download and then pass it to a custom download function like this: 我想异步从服务器检索一个ID,该ID对应于我要下载的文件,然后将其传递给自定义下载函数,如下所示:

<a href="{{=URL('custom_download',args = FILEID)}}" download>

This way, I will be able to upload files to the server asynchronously, (I already figured out how to do that) and the download link on the page for that file will work right away without having to reload the page. 通过这种方式,我将能够异步上传文件到服务器(我已经知道如何做到这一点),该文件页面上的下载链接将立即生效,无需重新加载页面。

So, on the server side, I would do something like this: 所以,在服务器端,我会做这样的事情:

def custom_download(): 
    download_row = db(db.computers.FILEID == request.args(0)).select()
    download_file = download_row.filefield
    return download_file

However, I'm not entirely sure what I need to write in order for this to work. 但是,我不完全确定我需要写什么才能使它工作。

I assumed that your files are stored in uploads folder, then your custom download function will be: 我假设您的文件存储在uploads文件夹中,那么您的自定义下载功能将是:

def custom_download():      
    download_row = db(db.computers.FILEID == request.args(0)).select().first()
    download_file = download_row.filefield

    # Name of file is table_name.field.XXXXX.ext, so retrieve original file name
    org_file_name = db.computers.filefield.retrieve(download_file)[0]
    file_header = "attachment; filename=" + org_file_name

    response.headers['ContentType'] = "application/octet-stream"
    response.headers['Content-Disposition'] = file_header

    file_full_path = os.path.join(request.folder, 'uploads', download_file)
    fh = open(file_full_path, 'rb')
    return response.stream(fh)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM