我遇到的问题是,即使成功将文件上传到Django服务器,jquery Form插件也不会触发'success'功能。
我的目标是使用jquery表单插件通过Ajax实现文件上传到Django服务器。文件上传本身有效。文件上传,服务器将“200 OK”响应返回给浏览器。什么行不通:我想根据从服务器返回的更新的图像文件路径替换img的'src'属性来更新页面上的图像。
这就是问题所在:jquery表单插件'success'函数未被调用,这意味着我无法更新页面上的图像。我已经跟踪了几乎所有描述类似问题的帖子,但到目前为止还没有成功。
以下是描述问题的更多细节:
以下是一些代码:
模板头:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
jquery的:
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
var message = '';
var options = {
dataType : 'json',
beforeSubmit: function() {
alert('file submitted');
},
success: function(response) {
console.log('Upload completed');
}
};
$('#uploadForm').ajaxForm(options);
});
</script>
html表格:
<span id="picture_upload_link">
<form id="uploadForm" class="input-file" action="{% url 'upload_profile_picture' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input name="user" type="hidden" value="{{ request.user.pk }}">
<input id="id_photo" class="input-file" name="photo" type="file">
<span class="upload-message"></span>
<input type="submit" value="Upload" />
</form>
</span>
<img id="user_photo" src="{{ MEDIA_URL }}{{ request.user.photo }}" class="profile_picture" />
models.py
class UserImage(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, blank=False)
photo = models.ImageField(blank=True, null=True, upload_to='profile_pictures', default='profile_pictures/no-img.jpg')
views.py
@login_required
def upload_profile_picture(request):
PhotoUploadForm = modelform_factory(UserImage, widgets = {'user':forms.HiddenInput(),})
response_data = {}
#m = UserImage.objects.get(user=request.user)
#print(PhotoUploadForm(instance=m))
if request.is_ajax():
m = UserImage.objects.get(user=request.user)
print('request is AJAX request')
form = PhotoUploadForm(request.POST, request.FILES, instance=m)
if form.is_valid():
print('form is valid')
form.photo = request.FILES['photo']
form.save()
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded:"
response_data['fileLink'] = "/%s" % m.photo
return HttpResponse(json.dumps(response_data), content_type="application/json")
else:
print('form is not valid')
print(form.errors)
else:
response_data['status'] = "error"
response_data['result'] = "We're sorry, but something went wrong. Please be sure that your file respects the upload conditions."
return HttpResponse(json.dumps(response_data), content_type='application/json')
服务器响应:
{"result": "Your file has been uploaded:", "status": "success", "fileLink": "/profile_pictures/example.JPG"}
我做错了什么?我一直在努力解决这个问题很长时间,并且感谢你的帮助。我更喜欢坚持使用jquery表单插件,尽管我愿意接受更好的解决方案。谢谢!