2015-01-07 3 views
0

그래서 Jquery Ajax를 사용하여 이미지를 Django 1.7 서버에 업로드하려고 할 때 몇 가지 문제가 발생합니다.Django + Jquery ajax 이미지 업로드 문제

기본적으로 내 개발 컴퓨터와 내 스테이징 시스템에서 발생하는 동작이 다르기 때문에 문제가 무엇인지 확인하기가 복잡해집니다. the file is not being uploaded for certain images.

웹 서버가 없는데 runserver을 사용하고 있습니다. 기본적으로 개발 (10MB)에서 큰 파일/큰 파일을 업로드하면 서버에 request.FILES이 비어 있습니다.

2MB 파일의 경우 내 로컬 컴퓨터가 올바르게 작동하고 설명서에 표시된 InMemoryUploadedFile을 사용하여 파일을 올바르게 업로드합니다 (small files 용). 준비에서 동일한 2MB 파일이 업로드되지 않습니다 (request.FILES이 서버에 비어 있음).

아이디어가 부족합니다. 누구에게 잘못되었거나 누락되었을 수 있는지에 대한 단서가 있습니까?

서버 :

class AjaxUploadImageView(UpdateView): 
    model = Multimedia 

    def get(self, request, *args, **kwargs): 
     return self.post(request, *args, **kwargs) 

    def post(self, request, *args, **kwargs): 
     self.object = self.get_object() 
     log.info(
      'Starting image upload process!!'.format(**locals()) 
     ) 
     if request.is_ajax(): 
      response = {} 
      log.info(
       'AjaxUploadImageView request.FILES: {request.FILES}' 
       .format(**locals()) 
      ) 
      if request.FILES.get('source_file'): 
       uploaded_img = request.FILES.get('source_file') 
       self.object.source_file.save(
        str(uploaded_img.name), File(uploaded_img) 
       ) 
       log.info(
        'It was uploaded: {self.object.source_file.url}' 
        .format(**locals()) 
       ) 
       response['source_file_url'] = self.object.source_file.url 
      else: 
       log.error(
        "There was no 'request.FILES.get('source_file')'!!" 
        .format(**locals()) 
       ) 
      return HttpResponse(
       json.dumps(response), content_type="application/json" 
      ) 

     else: 
      log.error(
       'There was no AJAX request!!'.format(**locals()) 
      ) 

      return HttpResponse(status=400) 

내 클라이언트 측 (에만 관련 무엇을 할 수 있음) :

<script type="text/javascript"> 
    var $ = django.jQuery; 
    $(document).ready(function(){ 
     // This code needs to live here so that Django's URL Reverse can work 

     // CSRF Token generation 
     function getCookie(name) { 
      var cookieValue = null; 
      if (document.cookie && document.cookie != '') { 
       var cookies = document.cookie.split(';'); 
       for (var i = 0; i < cookies.length; i++) { 
        var cookie = django.jQuery.trim(cookies[i]); 
        // Does this cookie string begin with the name we want? 
        if (cookie.substring(0, name.length + 1) == (name + '=')) { 
         cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
         break; 
        } 
       } 
      } 
      return cookieValue; 
     } 
     var csrftoken = getCookie('csrftoken'); 

     function csrfSafeMethod(method) { 
      // these HTTP methods do not require CSRF protection 
      return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
     } 
     function sameOrigin(url) { 
      // test that a given url is a same-origin URL 
      // url could be relative or scheme relative or absolute 
      var host = document.location.host; // host + port 
      var protocol = document.location.protocol; 
      var sr_origin = '//' + host; 
      var origin = protocol + sr_origin; 
      // Allow absolute or scheme relative URLs to same origin 
      return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || 
       (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || 
       // or any other URL that isn't scheme relative or absolute i.e relative. 
       !(/^(\/\/|http:|https:).*/.test(url)); 
     } 
     $.ajaxSetup({ 
      beforeSend: function(xhr, settings) { 
       if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { 
        // Send the token to same-origin, relative URLs only. 
        // Send the token only if the method warrants CSRF protection 
        // Using the CSRFToken value acquired earlier 
        xhr.setRequestHeader("X-CSRFToken", csrftoken); 
       } 
      } 
     }); 

     // Read a page's GET URL variables and return them as an associative array. 
     function getUrlVars(href) 
     { 
      if (!href) { 
       href = window.location.href; 
      } 
      var vars = [], hash; 
      var hashes = href.slice(href.indexOf('?') + 1).split('&'); 
      for(var i = 0; i < hashes.length; i++) 
      { 
       hash = hashes[i].split('='); 
       vars.push(hash[0]); 
       vars[hash[0]] = hash[1]; 
      } 
      return vars; 
     } 

     function ajaxImageUpload(obj_id) 
     { 
      var formData = new FormData($('form')[0]); 
      if (obj_id) { 
       $.ajax({ 
        url: "{% url 'core:ajax-upload-image' 999 %}".replace(999, obj_id), //Server script to process data 
        type: 'POST', 
        xhr: function() { // Custom XMLHttpRequest 
         var myXhr = $.ajaxSettings.xhr(); 
         return myXhr; 
        }, 
        //Ajax events 
{#     beforeSend: beforeSendHandler,#} 
        success: function(result){ 
         if(result.source_file_url){ 
          alert("The file was successfully uploaded!"); 
         } 
        }, 
        // Form data 
        data: formData, 
        //Options to tell jQuery not to process data or worry about content-type. 
        cache: false, 
        contentType: false, 
        processData: false 
       }); 
      } 
      else{ 
       alert("There is no ID"); 
      } 
     } 

     $('.available, .empty').click(function(e) { 
      e.preventDefault(); 

      var available_empty_url = $('.available, .empty').children('a').attr('href'); 
      var available_empty_language = getUrlVars(available_empty_url)['language']; 

      if (available_empty_language == 'en'){ 
       var current_language = 'fr' 
      } 
      else if (available_empty_language == 'fr'){ 
       var current_language = 'en' 
      } 

      var fields_to_save = $("#multimedia_form").serialize(); 
      var original_id = '{{ original.id }}'; 
      if (original_id) { 
       // Editing 
       var url = "{% url 'core:update-multimedia-admin-tab-info' 999 %}".replace(999, original_id) + "?language=" + current_language; 
       $.post(url, fields_to_save, function(data,status){ 
        if (status =='success') { 
         console.log("This tab was updated"); 
         var redirect_url = "{% url 'admin:core_multimedia_change' 999 %}".replace(999, data.obj_id) + '?language=' + available_empty_language; 
         ajaxImageUpload(data.obj_id); 
         window.location.href = redirect_url; 
        } 
       }); 
      } 
     }); 
    }); 
</script> 

어떤 아이디어 여기

내 코드?

답변

0

이미지 업로드시 jquery 호출을 동기화하기 위해 async: false을 추가하여이 문제를 해결했습니다. 모두에서 10MB 이미지를 테스트 한 결과