我正在替换现有的文件上传,它使用 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'
});