从fineuploader帖子中检索其他表单字段

时间:2013-10-08 12:24:20

标签: python fine-uploader

我正在替换使用html5和jquery的现有文件上传,将图像作为请求的一部分传递给python方法,该方法在存储图像和写入记录之前从请求中剥离图像和其他表单字段一个数据库。我希望使用Fineuploader库,并使用我的html表单成功发布到我的服务器:

$(document).ready(function(){
$('#manual-fine-uploader').fineUploader({
   request: {
        endpoint: apiPrefix + '/box/' + $('#boxId').val() + '/upload' + apiSuffix,
        inputName: 'photo_file'

   },
   dataType: 'json',
   autoUpload: false
})
   .on('submit', function(event, id, name) {
      $(this).fineUploader('setParams', {
        title: $('#title').val(),
        date: $("#date").val(),
        is_with: $('#is_with').val(),
        latitude: "0.0",
        longitude: "0.0",
        location_desc: $('#location').val(),
        photo_caption: $('#photo_caption').val()}, id);
   });

$('#triggerUpload').click(function() {
   $('#manual-fine-uploader').fineUploader('uploadStoredFiles');
});
});

这会在我的请求中添加其他参数,我可以在我的Python类中看到request.FILES['photo_file']有一个值,但之前我的python表单正在捕获其他表单数据:

class PhotoUploadAddForm(ModelForm):
class Meta:
    model = Entry
    exclude = ('type')

def __init__(self, *args, **kwargs):
    super(PhotoUploadAddForm, self).__init__(*args, **kwargs)

    self.fields['photo_caption'] = forms.CharField(required=False)
    self.fields['full_image_size'] = forms.IntegerField(required=False)
    self.fields['photo_file'] = forms.FileField(
        label='Select a file',
        help_text='max. 42 megabytes'
    )

然而,通过fineuploader发送请求我没有得到数据到我的模型中因此无法引用我的python类中的任何请求:

class BoxPhotoUploadView(View):
"""
Adds new Photo to a box
"""
form = PhotoUploadAddForm 
print 'BoxPhotoUploadView'
permissions = (IsAuthenticated, )
def post(self, request, box_id, width = None, height = None):
    try:
        user = get_user_from_request(request)
        userProf = UserProfile.objects.get(user = user)   

        print 'Adding photo to boxid=' + box_id            
        print request.FILES['photo_file']._name  

        if userCanWriteToBox(request, box_id) is True:
              full_image = None

            if "full_image_size" in self.CONTENT and self.CONTENT["full_image_size"] is not None:
                full_image_size = self.CONTENT['full_image_size']
                retina_photo = self.CONTENT['photo_file']
            else:              
                full_image = self.CONTENT['photo_file']
                full_image_size = getSizeOfImageInKB(full_image)
                retina_photo = resize_photo_to_constrains(self.CONTENT['photo_file'], 640, 960)

            boxCreator = getBoxCreator(int(box_id))
             new_space_used = int(boxCreator.space_used) + full_image_size # get size of photo and increase used space

            if boxCreator.usage_plan != None and new_space_used < boxCreator.usage_plan.max_size:   
                photo = Photo(
                  type = 'PH',
                  title = self.CONTENT['title'],
                  date = self.CONTENT['date'],
                  is_with = self.CONTENT['is_with'],
                  latitude = self.CONTENT['latitude'],
                  longitude = self.CONTENT['longitude'],
                  location_desc = self.CONTENT['location_desc'],
                  photo_pic = '',
                  photo_caption = self.CONTENT['photo_caption'],
                  photo_file = retina_photo,
                  photo_full_size = full_image_size
                )
                print 'Photo Details from Post: ' + str(photo)           
                photo.save()
                photo.photo_pic = settings.SERVER_URL + 'api/photo/' + str(photo.id) + '/'
                photo.save()

                if full_image is not None:                      
                    write_file_to_folder(full_image, photo.title, settings.FULL_IMAGES_FOLDER)

                print 'start resize ' + str(datetime.now())
                resizeImage(photo.photo_file, 180, 200)
                resizeImage(photo.photo_file, 240, 140)
                resizeImage(photo.photo_file, 200, 110)
                print 'finish resize ' + str(datetime.now())


                boxCreator.space_used = new_space_used
                boxCreator.save()

                assocEntryToBox(request, photo.id, box_id)
                aprvd = requiredAprroval(userProf, box_id)

                if aprvd == True:
                    return {"message":'Photo waiting for approval.','photo_id':photo.id, 'user_id':userProf.id}

                return {"message":'Photo added successfully to box', 'photo_id':photo.id, 'user_id':userProf.id}
            else:
                if boxCreator == userProf:
                    error_message = {"error_message":"You ran out of space to upload content"}
                else:
                    error_message = {"error_message":boxCreator.user.first_name + " " + boxCreator.user.last_name + " ran out of space to upload content"}

                return Response(status.HTTP_404_NOT_FOUND, error_message)

        else:
            return Response(status.HTTP_404_NOT_FOUND, {"error_message": 'Error adding photo to box.'})
    except Exception, e:
        print e
        return Response(status.HTTP_404_NOT_FOUND, {"error_message": 'Error adding photo.'})

为了补充一点,之前将文件传递给我的服务器的Jquery AJAX调用是:

var data = new FormData();

data.append("date", $("#fdate").val() );
data.append("is_with", $('#is_with').val() );
data.append("latitude", "0.0" );
data.append("longitude", "0.0" );
data.append("location_desc", $('#location').val() );
data.append("photo_caption", $('#photo_caption').val() );
data.append("photo_file",       

document.getElementById("photo_loader").files[0] );

    $.ajax(apiPrefix + '/photo/box' + apiSuffix, {
        data: data,
        processData: false,  // tell jQuery not to process the data
        dataType: "json",
        cache: false,
        beforeSend: function ( xhr ) {xhr.overrideMimeType("multipart/form-data")},
        contentType: false,   // tell jQuery not to set contentTypedata: data3 
    },
    type: 'POST'
});

1 个答案:

答案 0 :(得分:0)

您正在发送额外的表单数据客户端,但我相信您的服务器端实现不正确。 Django将传入的POST数据序列化为request.POST QueryDict source,并将传入的多部分编码文件序列化为request.FILES对象。您应该能够像任何其他Python字典一样访问传入的POST数据:

def post(self, request, box_id, width = None, height = None):
    # ...
    photo = Photo(
              type = 'PH',
              title = request.POST['title'],
              date = request.POST['date'],
              is_with = request.POST['is_with'],
              latitude = request.POST['latitude'],
              longitude = request.POST['longitude'],
              location_desc = request.POST['location_desc'],
              photo_pic = '',
              photo_caption = request.POST['photo_caption'],
              photo_file = retina_photo,
              photo_full_size = full_image_size
            )
    # ...