2011-01-20 4 views
8

간단한 AJAX 파일 업로드를 수행하려면 ajax-upload 코드를 사용하고 있습니다. 내가 겪고있는 문제는 제출 후 파일이 백엔드에 나타나지 않는다는 것입니다. Alex Kuhl에서 코드를 사용하여 나를 위해FileUpload with Django

def add_image(request, id): 
    print request 
    if request.FILES: 
     return HttpResponse("{success:true}") 
    else: 
     return HttpResponse("{success:false, message:'Unable to find FILES}") 

답변

12

는, request.GET['qqfile'] 파일 이름을했다 :

<div id="image_uploader">Upload More Images</div> 
<script type="text/javascript" charset="utf-8"> 
    function createUploader(){    
     var uploader = new qq.FileUploader({ 
      element: document.getElementById('image_uploader'), 
      action: '/add/image/1', 
      debug: true, 
      onSubmit : function() { 
       progress.show(); 
      }, 
      onComplete : function() { 
       progress.hide(); 
      }, 
      onCancel : function() { 
       progress.hide(); 
      }, 
     });   
    }; 

    createUploader(); 
</script> 

(현재 진행) 백엔드 코드는 아주 기본입니다 :

프론트 엔드 코드는 아주 기본입니다 request.read() (Django 1.3에서)이 데이터를 반환했습니다.

요청. 파일은 아직 나에게 발생하지 않은 시나리오에서만 사용되었습니다. 내가 Photologue에 직접 얘기 아약스 업로드를 사용하고, 내 코드는 다음과 같이 보입니다 : 내 경우

def save_upload(uploaded, filename, raw_data): 
    """ 
    raw_data: if True, upfile is a HttpRequest object with raw post data 
    as the file, rather than a Django UploadedFile from request.FILES 
    """ 
    try: 
     filename = os.path.normpath(os.path.join(IMAGE_UPLOAD_PATH, filename)) 
     with BufferedWriter(FileIO(filename, "wb")) as dest: 
      # if the "advanced" upload, read directly from the HTTP request 
      # with the Django 1.3 functionality 
      if raw_data: 
       (dirName, fileName) = os.path.split(filename) 
       (fileBaseName, fileExtension)=os.path.splitext(fileName) 
       # 
       # right here, if fileBaseName is less than n characters, might want to slap on a date just for fun 
       # 
       try: 
        i_can_has_p = Photo.objects.get(title=fileBaseName) 
        title = fileBaseName + "_" + str(datetime.datetime.now().strftime("%Y%m%dT%H%M%S")) 
       except Photo.DoesNotExist: 
        title = fileBaseName 
       title_slug = slugify(title) 
       p = Photo(title=title, title_slug=title_slug) 
       p.image.save(filename,ContentFile(uploaded.read())) 
      # if not raw, it was a form upload so read in the normal Django chunks fashion 
      else: 
       # TODO: figure out when this gets called, make it work to save into a Photo like above 
       for c in uploaded.chunks(): 
        dest.write(c) 
    except IOError: 
     # could not open the file most likely 
     return False 
    return True 

def ajax_upload(request): 
    if request.method == "POST": 
     # AJAX Upload will pass the filename in the querystring if it is the "advanced" ajax upload 
     if request.is_ajax(): 
      # the file is stored raw in the request 
      upload = request 
      is_raw = True 
      try: 
       filename = request.GET[ 'qqfile' ] 
      except KeyError: 
       return HttpResponseBadRequest("AJAX request not valid") 
     # not an ajax upload, so it was the "basic" iframe version with submission via form 
     else: 
      is_raw = False 
      if len(request.FILES) == 1: 
       # FILES is a dictionary in Django but Ajax Upload gives the uploaded file an 
       # ID based on a random number, so it cannot be guessed here in the code. 
       # Rather than editing Ajax Upload to pass the ID in the querystring, note that 
       # each upload is a separate request so FILES should only have one entry. 
       # Thus, we can just grab the first (and only) value in the dict. 
       upload = request.FILES.values()[ 0 ] 
      else: 
       raise Http404("Bad Upload") 
      filename = upload.name 

    # save the file 
    success = save_upload(upload, filename, is_raw) 

    # let Ajax Upload know whether we saved it or not 
    ret_json = { 'success': success, } 
    return HttpResponse(json.dumps(ret_json)) 

ajax_upload

+0

어디에서 IMAGE_UPLOAD_PATH를 정의 할 수 있습니까? –

+0

상수는 필요하지 않습니다. 천둥은 절대 경로를 만드는 데 단지 사용합니다. 상수 대신 업로드를 저장하려는 디렉토리에 하드 코딩 된 값을 사용할 수 있습니다. 그래도 사용하고 싶다면 settings.py에 놓은 다음 사용할보기로 가져와야합니다. 고개를 끄덕 어서 고마워, 다른 사람들이 내 게시물을 유용하다고 생각했습니다. –

+0

@alex : 좋아요, 저는 request.META [ 'PWD'] + "/ appName/static/images /"+ filename'을 사용하고 있습니다. –

1

앤드류 Valums 지금 가지고 아약스의 action: 매개 변수에 의해 호출하는 기능입니다 a django app git hub에서