开发者

Django/jQuery - read file and pass to browser as file download prompt

开发者 https://www.devze.com 2023-01-03 16:34 出处:网络
I\'ve previously asked a question regarding passing files to the browser so a user receives a download prompt.However these files were really just strings creatd at the end of a function and it was si

I've previously asked a question regarding passing files to the browser so a user receives a download prompt. However these files were really just strings creatd at the end of a function and it was simple to pass them to an iframe's src attribute for the desired effect.

Now I have a more ambitious requirement, I need to pass pre existing files of any format to the browser. I have attempted this using the following code:

def return_file(request):

    try:
        bob=open(urllib.unquote(request.POST["file开发者_开发百科"]),"rb")

        response=HttpResponse(content=bob,mimetype="application/x-unknown")
        response["Content-Disposition"] = "attachment; filename=nothing.xls"
        return HttpResponse(response)
    except:
        return HttpResponse(sys.exc_info())

With my original setup the following jQuery was sufficient to give the desired download prompt:

jQuery('#download').attr("src","/return_file/"); 

However this won't work anymore as I need to pass POST values to the function. my attempt to rectify that is below, but instead of a download prompt I get the file displayed as text.

jQuery.get("/return_file/",{"file":"c:/filename.xls"},function(data)
{
    jQuery(thisButton).children("iframe").attr("src",data);
});

Any ideas as to where I'm going wrong?

Thanks!

EDIT:

I've now changed everything so that passing the filename using POST returns an id number retrieved from the database which when appended to the URL causes the file to be returned. Thus /return_file/1/ returns a file with id 1.

jQuery('#download').attr("src","http://localhost/return_file/1/");

where "download" is the id of an iframe.

There must be a better way of dealing with file downloads. Does anyone have ideas for a better method?


Why not just use bob.read() the same way you previously used a differently-constructed string? Seems simplest!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号