我正在替換現有的文件上傳,它使用html5和jquery將圖像作爲請求的一部分傳遞給一個python方法,該方法將圖像和其他表單域從請求中剝離存儲圖像並將記錄寫入數據庫。我希望能使用Fineuploader庫,我有我的HTML表單使用成功發佈到我的服務器:從fineuploader帖子檢索額外的表單域
$(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'
});
您認爲'self.CONTENT'是什麼?你在使用Django還是類似的東西?我知道Django將'request.FILES'和POST請求數據上傳到'request.POST'中(https://docs.djangoproject.com/en/1.6/ref/request-response/#httprequest-objects) –
請在您的問題中顯示上傳請求的內容。例如,您可以使用Chrome的網絡標籤獲取此信息。 –