python 访问网址下载(浏览器打开另存为对话框)

一.python 函数返回式下载,话不多说上代码

  

def xxx(request):
  filename=''

  fp = open(filename,'rb')
  mydata = fp.read()
  fp.close()
response = HttpResponse(mydata, mimetype='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename="%s"'%filename.split('/')[-1]
return response

直接读取所要下载内容,response 文件内容和要保存的文件名就ok.

二.字段解析

  1. disposition := "Content-Disposition" ":"
  2.  
    disposition- type
  3.  
    *( ";" disposition-parm)
  4.  
    disposition- type := "inline"
  5.  
    / "attachment"
  6.  
    / extension-token
  7.  
    ; values are not case-sensitive
  8.  
    disposition-parm := filename-parm / parameter
  9.  
    filename-parm := "filename" "=" value;

Content-Disposition属性有两种类型:inline 和 attachment inline :将文件内容直接显示在页面 attachment:弹出对话框让用户下载具体例子:

  1.  
    Content- Type: image/jpeg   可选
  2.  
    Content-Disposition: inline;filename=hello.jpg
  3.  
    Content-Description: just a small picture of me

在页面内打开代码:

  1.  
    File file = new File("rfc1806.txt");
  2.  
    String filename = file.getName();
  3.  
    response.setHeader("Content-Type","text/plain");
  4.  
    response.addHeader("Content-Disposition","inline;filename=" + new String(filename.getBytes(),"utf-8"));
  5.  
    response.addHeader("Content-Length","" + file.length());

弹出保存框代码:

    1.  
      File file = new File("rfc1806.txt");
    2.  
      String filename = file.getName();
    3.  
      response.setHeader("Content-Type","text/plain");
    4.  
      response.addHeader("Content-Disposition","attachment;filename=" + new String(filename.getBytes(),"utf-8"));
    5.  
      response.addHeader("Content-Length","" + file.length());
      python  
       
        
       

猜你喜欢

转载自www.cnblogs.com/nanyu/p/9647325.html