2017-12-28 31 views
0

아래 아약스 전화가 있습니다. 이제 url/api/create/project에 파일을 포함한 데이터를 게시하고 싶습니다.djangorest API에 ajax를 사용하여 파일을 업로드 하시겠습니까?

$(document).ready(function(){ 
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 = 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)); 
} 


$(".project").submit(function(event){ 
     event.preventDefault() 
     var image_file = document.getElementById('content'); 
     var myFile = image_file.files[0]; 
     console.log(myFile); 
     var this_ = $(this); 
     var form = this_.serializeArray(); 
     console.log("form", this_); 
     console.log(form); 
     var formData = this_.serialize(); 

     var temp= 

     { 
"title": form[1].value, 
"project_question_content_url": myfile, 
"deadline_date": form[2].value, 
"employee": {{ id }}, 
"course": form[3].value 

}

console.log(temp); 
     $.ajax({ 
     url: "/api/project/create", 
     data: JSON.stringify(temp), 
     beforeSend: function(xhr, settings) { 
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) { 
     xhr.setRequestHeader("X-CSRFToken", csrftoken); 
    } 
    }, 

     method: "POST", 
     contentType: "application/json; charset=utf-8", 
     dataType: 'json', 
     success: function(data){ 
      console.log(data) 


     }, 
     error: function(data){ 
      console.log("error") 
      console.log(data.statusText) 
      console.log(data.status) 
     } 
     }) 

    }); 
    }); 

지금, 어떻게 임시 변수에 JSON을 통해 파일을 보낼? 나머지 프레임 워크를 사용하여 API를 만들었습니다. 또한 보안상의 이유로 js의 파일 경로 URL을 얻을 수 없습니다. 나머지 파일 업로드는 정상적으로 작동합니다. 도와주세요!

답변

0

브라우저에서 파일을 업로드하기 위해 자체 구현을 사용하는 대신 https://github.com/blueimp/jQuery-File-Upload과 같은 패키지를 사용하면 경험을 단순화 할 수 있습니다. 주요 문제는 XHR 개체에 파일 데이터를 첨부해야한다는 것입니다.이 작업에는 여러 단계가 필요합니다. 위에서 링크 된 파일 업 로더 위젯과 같은 것을 사용하면 훨씬 쉽게 통합 할 수 있으며 많은 유용한 기능이 포함되어 있습니다.

브라우저에서 작업 한 후에는 기존 API와의 통합이 쉬워야합니다.

+0

jquery file upload 사용하기 작동하지만 어떻게 ajax 데이터를 통해 파일 데이터를 보낼 수 있습니까? – nope

+0

당신은 lib가 그것을하는 방법을 볼 수 있습니다 – Jason

+0

파일 업로드는 라이브러리와 함께 작동합니다 .. 그 점에 대해 감사합니다 !! 하지만 아약스 게시 메서드를 통해 보낸 미디어 폴더에서 URL을 작동하지 않습니다 .. 어떤 생각? – nope