前端:
<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'), ]