1/5 (1) Upload/download file to/from server in Django via AJAX

...
<input id="table-input-user-file" class="table-input-user-file" type="file" name="table-input-user-file">
<input id="table-input-user-id" class="table-input-user-id" type="hidden" name="table-input-user-id">
<input class="popup-item item-button-upload" data-user-id="${user.id}" type="submit" value="Upload"/> <br/>
<input class="popup-item item-button-download" data-user-id="${user.id}" type="submit" value="Download"/>
...
//Upload/Download Rows Action
let inputUserFile = $('#rawTable').find('.table-input-user-file[type=file]')
let inputUserId = $('#rawTable').find('.table-input-user-id[type=hidden]')
//
$('.item-button-upload').on('click', function(){
  inputUserId.val($(this).attr("data-user-id"))
  inputUserFile.click()
})
$('.item-button-download').on('click', function(e){
  e.preventDefault();
  location.href = location.href + 'download?id='  + $(this).attr("data-user-id")
})
inputUserFile.on('change', ()=>{
  var formData = new FormData()
  formData.append('id', inputUserId.val())
  formData.append('file', inputUserFile[0].files[0])

  let csrfToken = jQuery("[name=csrfmiddlewaretoken]").val();
  $.ajax({
    url: "upload/",
    method: "POST",
    data: formData,
    cache: false,
    processData: false,
    contentType: false,
    enctype: 'multipart/form-data',
    headers: {
      "X-CSRFToken": csrfToken,
    },
    success: (e) => { console.log('Success!', e) },
    error: (e) => { console.error(e) },
    complete: () => { },
  })
})
from django.urls import path

from . import views


app_name = 'MyApp'

urlpatterns = [
    ...
    path('upload/', views.DownloadView.as_view(), name='upload'),
    path('download/', views.DownloadView.as_view(), name='download'),
    ...
]
from wsgiref.util import FileWrapper
from shutil   import make_archive
from django.core.files.storage import FileSystemStorage
from myapp import settings

...
class UploadView(LoginRequiredMixin, View, AjaxMixin, FilterMixin):
    def post(self, request, *args, **kwargs):
            upload_file = request.FILES['file']
            fs = FileSystemStorage()
            fs.save('uploads/' + request.POST['id'] + '/' + upload_file.name, upload_file)
            return HttpResponse('')

class DownloadView(LoginRequiredMixin, View, AjaxMixin, FilterMixin):
    def get(self, request, *args, **kwargs):
            user_folder = request.GET['id']
            files_path = os.path.join(settings.MEDIA_ROOT, "uploads/") + user_folder
            if not os.path.exists(files_path):
                os.mkdir(files_path)
            path_to_zip = make_archive(files_path, "zip", files_path)
            response = HttpResponse(FileWrapper(open(path_to_zip,'rb')), content_type='application/zip')
            response['Content-Disposition'] = 'attachment; filename="{filename}.zip"'.format(
                filename = user_folder.replace(" ", "_")
            )
            os.remove(files_path + '.zip')
            return response
...

Пожалуйста, оцените материал

WebSofter

Web - технологии