随笔 - 911  文章 - 5  评论 - 94  阅读 - 243万

django文件上传下载

views:

复制代码
def mgmt_files(request): #列出树形目录,上传文件页面
    if request.method == 'POST':
        path_root = "D:\\py\\ITFiles" #上传文件的主目录
        myFile =request.FILES.get("file", None)    # 获取上传的文件,如果没有文件,则默认为None  
        if not myFile:  
            dstatus = "请选择需要上传的文件!"
        else:
            path_ostype = os.path.join(path_root,request.POST.get("ostype"))
            path_dst_file = os.path.join(path_ostype,myFile.name)
            # print path_dst_file
            if os.path.isfile(path_dst_file):
                dstatus = "%s 已存在!"%(myFile.name)
            else:
                destination = open(path_dst_file,'wb+')    # 打开特定的文件进行二进制的写操作  
                for chunk in myFile.chunks():      # 分块写入文件  
                    destination.write(chunk)  
                destination.close()  
                dstatus = "%s 上传成功!"%(myFile.name)
        return HttpResponse(str(dstatus))

    return render(request,'sinfors/mgmt_files.html')


def mgmt_file_download(request,*args,**kwargs): #提供文件下载页面
    #定义文件分块下载函数 
    def file_iterator(file_name, chunk_size=512):
        with open(file_name,'rb') as f: #如果不加‘rb’以二进制方式打开,文件流中遇到特殊字符会终止下载,下载下来的文件不完整
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    path_root = "D:\\py\\ITFiles"
    if kwargs['fpath'] is not None and kwargs['fname'] is not None:
        file_fpath = os.path.join(path_root,kwargs['fpath']) #kwargs['fapth']是文件的上一级目录名称
        file_dstpath = os.path.join(file_fpath,kwargs['fname']) #kwargs['fname']是文件名称

        response = StreamingHttpResponse(file_iterator(file_dstpath))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(kwargs['fname']) #此处kwargs['fname']是要下载的文件的文件名称
        return response
复制代码

  StreamingHttpResponse对象用于将文件流发送给浏览器,与HttpResponse对象非常相似,对于文件下载功能,使用StreamingHttpResponse对象更合理。通过文件流传输到浏览器,但文件流通常会以乱码形式显示到浏览器中,而非下载到硬盘上,因此,还要在做点优化,让文件流写入硬盘,给StreamingHttpResponse对象的Content-Type和Content-Disposition字段赋下面的值即可,如:

response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="filename.txt"'

 

 

html页面:

复制代码
 <form id="uploadForm" enctype="multipart/form-data"> //文件上传的form
            {% csrf_token %}
            <input id="file" type="file" name="file" > //上传文件
            <input type="radio" name="ostype" value="Windows" />Windows 
            <input type="radio" name="ostype" value="Linux" />Linux
            <input type="radio" name="ostype" value="Network" />Network
            <input type="radio" name="ostype" value="DB" />DB
            <button id="upload" type="button" style="margin:20px">上传</button>
</form>
复制代码

js页面:

复制代码
  $("#upload").click(function(){
    // alert(new FormData($('#uploadForm')[0]));
    var ostype = $('input:radio:checked').val()
    if (ostype == undefined){
      alert('请选择上传的文件类型');
    }
     //获取单选按钮的值
    $.ajax({
            type: 'POST',
            // data:$('#uploadForm').serialize(),
            data:new FormData($('#uploadForm')[0]),
            processData : false,   
            contentType : false, //必须false才会自动加上正确的Content-Type  
            // cache: false,
            success:function(response,stutas,xhr){
              // parent.location.reload();
              //window.location.reload();
              // alert(stutas);
              alert(response);
            },
            // error:function(xhr,errorText,errorStatus){
            //   alert(xhr.status+' error: '+xhr.statusText);
            // }
            timeout:6000
        });

  });
复制代码

 

posted on   momingliu11  阅读(5981)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2013-10-11 Windows Server 2012远程刷新客户端组策略,IE代理设置
2013-10-11 关于单一网络适配器拓扑TMG
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示