js
// 发送文件
$(".filebtn").click(function () {
var formdata=new FormData();
formdata.append("file_obj",$("#file")[0].files[0]);
formdata.append("user",$("#user").val());
$.ajax({
url:"/file_put/",
type:"post",
// Ajax上传文件必备参数
processData: false , // 不处理数据
contentType: false, // 不设置内容类型
data:formdata,
success:function (response) {
console.log(response);
if (response=="OK"){
$(".msg").html("提交成功!")
}
}
})
})
def file_put(request):
print(request.POST)
print(request.FILES)
file_obj=request.FILES.get("file_obj")
# 文件对象有一个name属性,获取文件名称字符串
print(file_obj.name)
path=file_obj.name
path=os.path.join(settings.BASE_DIR,"media","img",path)
with open(path,"wb") as f:
for line in file_obj:
f.write(line)
return HttpResponse("OK")
注意: csrf跨站请求伪造 。