美文网首页
Django从0到1用uploadify实现文件上传功能

Django从0到1用uploadify实现文件上传功能

作者: 西电大侠 | 来源:发表于2018-03-21 10:26 被阅读72次

    本人环境 Debian Django 1.11 uploadify官网下载最新版。

    uploadify官网demo写的很简单。而且不是基于django的,所以可能要花些时间做些研究,我去网上搜了django uploadify,发现介绍的都很简单,而且最关键的坑都没指出来。之前自己用过uploadify,成功过,后来过了很久再做,还是花了几个小时才配置成功,所以,这次一定要详细记录碰到的坑。

    直接上代码,有问题可留言讨论。
    html需要添加核心代码:

    <link href="{% static "uploadify" %}/uploadify.css" rel="stylesheet">
    
    <div class="demo-box">  
           <input id="file_upload" type="file" name="Filedata">  
           <div id="file_uploadQueue" class="uploadifyQueue"></div>  
           <p><span id="id_span_msg"></span></p>  
    </div>
    
    <script src="{% static "uploadify" %}/swfobject.js"></script>
    <script src="{% static "uploadify" %}/jquery.uploadify.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {  
          var file_name='';  
          $('#file_upload').uploadify({  
            'uploader'  : "{% url 'uploadify_script' %}",//根据文件存放地址改变 或者使用'/upload_script/'
            'swf' : '/static/uploadify/uploadify.swf', 
            'cancelImg' : '/static/uploadify/uploadify-cancel.png',//根据文件存放地址改变  
            'folder'    : '/upload',  
            'auto'      : true,//false,//  
            'multi': true,//设置可以上传多个文件  
            'queueSizeLimit' : 30,  
            'buttonText':'文件上传',     
            'removeCompleted':false,//  
            'fileSizeLimit':10240000,//设置上传文件大小单位kb  
            'fileTypeExts':'*.xlsx',//设置上传文件类型为常用文档格式  
            'fileTypeDesc':'支持文档格式',                  
            'onInit': function () {},  
            'onError': function (event,ID,fileObj,errorObj) {  
                    $('#id_span_msg').html("上传失败,错误码:"+errorObj.type+" "+errorObj.info);  
                },  
            'onSelect': function (e, queueId, fileObj) {  
                $('#id_span_msg').html("");  
            },  
            'onCancel': function(event,ID,fileObj,data) {  
              $.post("/delete_uploadfile/", { delete_file: file_name } );  
              file_name='';  
            }, 
            'onComplete': function(event, ID, fileObj, response, data) {  
                var result = eval ("(" + response + ")");  
                file_name=result.save_name;  
            },
            'onUploadSuccess': function(file, data, response) {
                alert('The file was saved to: ' + data);
            }
          });  
        });
            </script>
    

    关键的参数 uploader 和 swf,其他可照抄。
    uploader是服务器脚本位置 可以用url方式写,也可以用/upload_script/写试试。不要用官网demo的php脚本。
    不过切记,这里的url是在你的Django最顶层的url里面写的,因为我的服务器脚本是在invest app里的view写的,那你需要在最顶层的url这么写。

    顶层url文件,需要添加:

    from invest import views
    url(r'^upload_script/$', views.uploadify_script, name='uploadify_script'),
    

    刚开始是在invest app里的url填的这些,运行报错
    Reverse for 'uploadify_script' not found. 'uploadify_script' is not a valid view function or pattern name.百思不得其解。后来还是看自己之前的写的程序,发现在顶层写的,后来再回过头来看,这个报错,其实已经说得很清楚了,就是url没有配置,但是我确实配置了,说明配置的地方不对,其实还是敏感度不够。
    注意,url写法,后面跟的是name,链接用的是/upload_script/。

    view.py需添加:

    import os
    import uuid
    from django.views.decorators.csrf import csrf_exempt, csrf_protect
    
    def save_uploaded_file(f, filename):
        destination = open(filename, 'wb')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
    def multiFileUpload(fileContent):
        addr = str(uuid.uuid3(uuid.NAMESPACE_OID, str(fileContent.name)))
        path = os.path.join(static_path, addr)
        if not os.path.exists(path):
            os.mkdir(path)
        filename = os.path.join(path, fileContent.name)
        new_name = filename
        save_uploaded_file(fileContent, filename)
    
        return (True,new_name)
    
        
    @csrf_exempt
    def uploadify_script(request):
        print 'upload..........'
        ret="0"  
        new_name = ''
        #request.FILES['data']
        filename = request.FILES.get("Filedata",None)
        # if request.FILES and request.FILES['Filedata']:
        #   print request.FILES['Filedata'].name
        # print 'here'
        # filename = request.FILES['Filedata'].name
        print 'filename '+filename.name
        if filename:
            result,new_name=file_upload(filename)
            if result:
                ret="1"
            else:
                ret="2"
        import json            
        source={'ret':ret,'save_name':new_name}
        print source
        return HttpResponse(json.dumps(source))
      
      
    def file_upload(filename):  
        '''''文件上传函数'''  
        if filename:
            print 'file_upload'
            path=os.path.join(static_path,'upload')
            if not os.path.exists(path):
                os.mkdir(path,0755)
            print path
            #file_name=str(uuid.uuid1())+".jpg"  
            file_name=str(uuid.uuid1())+'-'+filename.name
            #fname = os.path.join(settings.MEDIA_ROOT,filename)
            path_file=os.path.join(path,file_name)
            print file_name
            print path_file
            fp = open(path_file, 'wb')
            for content in filename.chunks():
                fp.write(content)
            fp.close()
            return (True,file_name) #change
        return (False,file_name)   #change
      
    #用户管理-添加用户-删除附件  
     
    @csrf_exempt
    def file_delete(request):  
        del_file=request.POST.get("delete_file",'')  
        if del_file:  
            path_file=os.path.join(settings.MEDIA_ROOT,'upload',del_file)  
            os.remove(path_file)
    

    另一个是windows和linux的路径写法不同,以及创建目录的方法略有不同,linux需要加上权限参数,windows不需要。
    windows:
    static_path = 'j:\work_netease\my_site\web_performance\draw\static\pic'
    if not os.path.exists(path):
    os.mkdir(path)

    linux:
    static_path = '/home/website/demo/mysite/invest/static/'
    if not os.path.exists(path):
    os.mkdir(path,0755)

    name 'csrf_exempt' is not defined
    Django官网搜csrf_exempt 可以很容易找到这一行
    from django.views.decorators.csrf import csrf_exempt, csrf_protect

    关于最前面的swfobject.js,那他究竟是什么呢?
    最近看到了好几个Flash网站,head代码里都加载了一个swfobject.js,这个JS究 竟有什么作用呢?眼下正在做一个Web页面,说不定刚好可以派上用场。于是,好奇的搜索了一下。原来这是老外开发的,用于在HTML中方面插入Adobe Flash媒体资源(*.swf文件)的独立、敏捷的JavaScript模块,该模块中的JavaScript脚本能够自动检测PC、Mac机器上各种 主流浏览器对Flash插件的支持情况。目前最新的版本是2.2,这里可以下载最新版的SWFObject

    相关文章

      网友评论

          本文标题:Django从0到1用uploadify实现文件上传功能

          本文链接:https://www.haomeiwen.com/subject/nwywqftx.html