JS 获取多张图片(作为 FormData)到 Django 保存
JS fetch multiple pics (as FormData) to Django to save
我确定这看起来很基础,但这是我第一次尝试使用 fetch 将文件上传到 Django,我不确定如何在 Django 中操作和访问 FormData。
这个创建如此许多非工作的 jpg 文件。如何解决?
HTML:
<div>
<textarea></textarea>
<input type="file" multiple></input>
<button onClick="dothis()" >Sound</button>
</div>
JS:
function dothis(){
let data = new FormData();
let input = event.target.previousElementSibling;
for (let file of input.files){
d.append( "hello", file);
}
fetch("/images", {
credentials: "include",
method: "POST",
mode: "same-origin",
headers: {
"Accept": "application/json",
"Content-Type": "application/json", // or "multipart/form-data"??
"X-CSRFToken": csrf
},
body: data
})
.then(response => response.json())
.then(result => {
console.log("Well?");
})
Django views.by:
def images(request):
print(request.body)
form = request.body
filename = 0
for ff in form:
filename += 1
with open(f"{filename}.jpg", "wb+") as f:
f.write(ff)
return JsonResponse(status=201)
想通了...
从 fetch 的 headers
和
中删除了 Content-Type
使用 request.FILES
访问了 views.by 中的文件
我确定这看起来很基础,但这是我第一次尝试使用 fetch 将文件上传到 Django,我不确定如何在 Django 中操作和访问 FormData。
这个创建如此许多非工作的 jpg 文件。如何解决?
HTML:
<div>
<textarea></textarea>
<input type="file" multiple></input>
<button onClick="dothis()" >Sound</button>
</div>
JS:
function dothis(){
let data = new FormData();
let input = event.target.previousElementSibling;
for (let file of input.files){
d.append( "hello", file);
}
fetch("/images", {
credentials: "include",
method: "POST",
mode: "same-origin",
headers: {
"Accept": "application/json",
"Content-Type": "application/json", // or "multipart/form-data"??
"X-CSRFToken": csrf
},
body: data
})
.then(response => response.json())
.then(result => {
console.log("Well?");
})
Django views.by:
def images(request):
print(request.body)
form = request.body
filename = 0
for ff in form:
filename += 1
with open(f"{filename}.jpg", "wb+") as f:
f.write(ff)
return JsonResponse(status=201)
想通了...
从 fetch 的 headers
和
中删除了 Content-Type
使用 request.FILES