码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-08-15 11:12:58      阅读:330      评论:0      收藏:0      [点我收藏+]

标签:headers   cti   efault   ons   token   form   style   console   class   

前端:

<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),
]

 

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

标签:headers   cti   efault   ons   token   form   style   console   class   

原文地址:https://www.cnblogs.com/52-qq/p/9480142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!