2011-01-20 18 views
8

Sto usando il codice ajax-upload per fare un semplice caricamento di file AJAX. Il problema che sto riscontrando è che il file non viene visualizzato sul back-end dopo l'invio.FileUpload con Django

Il codice frontend è piuttosto semplice:

<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> 

Il codice backend (attualmente in corso) è anche piuttosto semplice:

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

risposta

12

Per me, utilizzando il codice da Alex Kuhl, request.GET['qqfile'] avevano il nome del file e request.read() (in Django 1.3) ha restituito i dati.

request.FILES è stato utilizzato solo in uno scenario che non è ancora accaduto per me. Sto usando ajax-upload di parlare direttamente con Photologue, e il mio codice simile a questa:

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)) 

Nel mio caso, ajax_upload è la funzione chiamata dal parametro di ajax action:

+0

Dove posso definire "IMAGE_UPLOAD_PATH"? –

+0

Quella costante non è richiesta, Thunder si sta semplicemente servendo di essa per costruire un percorso assoluto. È possibile utilizzare un valore hardcoded per la directory in cui si desidera salvare i caricamenti anziché la costante. Se vuoi usarlo però, sarebbe qualcosa che inserisci in settings.py e poi importa nella vista da usare. Anche grazie per il cenno del capo, gli altri contenti hanno trovato utile il mio post. –

+0

@alex: Ok, sto usando 'request.META ['PWD'] +"/appName/static/images/"+ filename'. –

Problemi correlati