• 文件上传自动生成日期文件夹


    前端:

    <div class="container">
        <form action="">
            {% csrf_token %}
            <div class="col-md-4 col-md-offset-4">
            <div class="form-group">
                <input type="file" name="file" id="file_upload">
            </div>
        </div>
        </form>
        <button type="button" class="btn btn-default" id="btn_file">点击上传</button>
    </div>
    
    <script>
        $("#btn_file").click(function () {
            var form_data = new FormData();
            var file_info = $('#file_upload')[0].files[0];
            form_data.append('file', file_info);
            if (file_info == undefined){
                console.log('没有选择任何文件');
                return false
            }
            $.ajax({
                url: '{% url "uploadFile" %}',
                type: 'POST',
                headers:{"X-CSRFToken":$.cookie('csrftoken')},
                data: form_data,
                contentType:false,
                processData:false,
                success:function (data) {
                    console.log(data)
                }
            })
        })
    </script>

    后端:

    def uploadFile(request):
        from finanical import settings
        file_obj = request.FILES.get('file')
        file_name = file_obj.name
        time_path = time.strftime('%Y-%m-%d', time.localtime())
        path = os.path.join(settings.MEDIA_ROOT, time_path)
        if not os.path.exists(path):
            os.mkdir(path)
        path = os.path.join(path + '/' + file_name)
        with open(path, 'wb') as f:
            for i in file_obj.chunks():
                f.write(i)
        response = {
            'error': 0,
            'url': 'media/' + time_path + file_name + '/'
        }
        return HttpResponse(json.dumps(response))

    还需要配置url

    from django.conf.urls import url
    from django.contrib import admin
    from django.views.static import serve
    from finanical import settings
    from api import views
    import xadmin
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^xadmin/', xadmin.site.urls),
        url(r'^index/', views.index, name='index'),
        url(r'^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}),
        url(r'^uploadFile/$', views.uploadFile, name='uploadFile'),
    ]
  • 相关阅读:
    纯CSS3实现不错的表单验证效果
    CANVAS模仿龙卷风特效
    HTML+CSS画一朵向日葵
    canvas水波纹效果
    樱花的季节,教大家用canvas画出飞舞的樱花树
    网站SEO,HTTP请求的关键数字----6
    css3绘制腾讯logo
    关于js的parseInt方式在不同浏览器下的表现
    封装keyframes插件
    模仿jquery的fileupload插件
  • 原文地址:https://www.cnblogs.com/52-qq/p/9480142.html
Copyright © 2020-2023  润新知