我在尝试通过 AJAX 请求向 Django 发送图像时遇到问题。 这是我的 HTML:
<form>
<input type="file" id="files" name="image">
</form>
这是我的 JS:
var control = document.getElementById("files");
var p = {
title: $('input[name=title]').val(),
subtitle: $('input[name=subtitle]').val(),
content: $('textarea#article-content').val(),
image: files[0],
};
$.ajax({
url: '/prive/nouveau-projet',
type: "POST",
data: JSON.stringify(p),
crossDomain: true,
success: function() {
window.location.href = '/prive/projets/';
},
error: function() {
console.log("error");
}
});
这是我的服务器端代码:
if request.method == "POST":
data = request.POST.keys()[0]
dataJson = json.loads(data)
p = Projet(title=dataJson['title'], subtitle=dataJson['subtitle'], content=dataJson['content'], image=dataJson['image'])
p.save()
return HttpResponse()
这就是我尝试过的,但我收到有关 dataJson['image']
的错误。你能帮我一下吗?
最佳答案
你不需要JSON.stringify
。
就这样写:
var data = new FormData();
var img = $('#image_field_id')[0].files[0];
data.append('img', img);
$.ajax({
url : "/prive/nouveau-projet",
processData : false,
contentType : false,
type : 'POST',
data : data,
}).done(function(data) {
// work with data
});
在 View 中
if request.method == "POST":
file = request.FILES.get('img') # FILES instead of POST
....
关于javascript - 通过Ajax发送文件到Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27488832/