我正在尝试使用Django上传和保存图像文件,并响应图像本身,以便在javascript函数中使用。
问题是图像没有保存,.FILES请求是空的。
在使用request.body时,我可以看到没有实际的文件路径,只有C://fakepath。
因为我希望立即保存上传的图像,所以我使用了jQueryAjax调用进行发布,然后保存数据,创建一个新对象,然后函数将返回一个成功的结果。
views.py:
def image_feedback(request):
if request.method == 'POST':
image = request.FILES.get('image')
ImagesUpload.objects.create(
image = image,
)
return HttpResponse('success')
models.py:
class ImagesUpload(models.Model):
image = models.ImageField(upload_to=renaming_file)
def __str__(self):
return str(self.image)
form_template.html:
<form id="image_form" enctype="multipart/form-data">{% csrf_token %}
<button class="btn btn-secondary" onclick="$('#id_image').click()">Import Image</button>
{{ form_image.image }}
<input id="hidden-submit-img" value="SUBMIT" type="submit" style="visibility:hidden">
</form>
jquery ajax 调用:
<script>
$(document).ready(function () {
// This jquery changes the appearance of the django { form_image }
var imgElement = $('#id_image');
imgElement.css('visibility', 'hidden');
// This function triggers the hidden submit,
// which triggers the ajax image request
imgElement.on({
change: function () {
$('#hidden-submit-img').click();
},
});
});
// This jquery is for the ajax post of the image
$('#image_form').submit(function (event) {
event.preventDefault();
$.ajax({
data: {
image: $('#id_image').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
type: "POST",
enctype: 'multipart/form-data',
url: "{% url 'website:image-feedback' %}",
success: function (data) {
console.log(1);
console.log(data)
},
error: function (data) {
console.log(0);
}
});
});
</script>
我认为图像无法保存是因为JavaScript无法通过正确的路径,但是该如何解决呢?
更新:
在ajax调用中将事件从.submit更改为.change时,图像会被保存,我可以在浏览器中看到成功的console.log,但是HttpResponse('success')呈现了一个新的空白页面,其中仅包含“ succes”字眼。 如何防止HttpResponse这样做? 将事件改回.submit可以防止页面重新加载,但是无法保存图像。
这是我的新ajax调用,views.py保持不变:
// This jquery is for the ajax post of the image
// Doing it with submit, the image wont get saved, but the request is "success"
// $('#image_form').submit(function (event) {
// Doing it with change, the image gets saved successfully,
// the console logs the success
// but the respond loads a new page
$('#image_form').change(function (event) {
event.preventDefault();
$.ajax({
data: {
image: $('#id_image').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
enctype: 'multipart/form-data',
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function (data) {
console.log(1);
console.log(data)
},
error: function (data) {
console.log(0);
}
});
});