文件上傳自動生成日期文件夾
阿新 • • 發佈:2018-08-15
token info formdata nbsp err data oca error resp
前端:
<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‘), ]
文件上傳自動生成日期文件夾