django项目中form表单和ajax的文件上传功能。

form表单文件上传

路由

# from表单上传
path('formupload/',apply.formupload,name='formupload/'),

方法

# form表单文件上传
def formupload(request):
if request.method == 'POST':
image_obj = request.FILES.get('headimg')
print(image_obj)
with open(settings.MEDIA_ROOT+'/'+image_obj.name,'wb') as f:
for lin in image_obj:
f.write(lin)
return HttpResponse('ok')

前端html

<form action="/apply/formupload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="headimg">
<input type="submit" value="form表单上传">
</form>

上传成功示例

django项目中form表单和ajax的文件上传功能。

#ajax上传

路由

# ajax上传文件
path('ajaxupload/',apply.ajaxupload,name='ajaxupload/'),

方法

# ajax文件上传
def ajaxupload(request):
if request.method == 'POST':
image_obj = request.FILES.get('headimg')
print(image_obj)
with open(settings.MEDIA_ROOT + '/' + image_obj.name, 'wb') as f:
for lin in image_obj:
f.write(lin)
return HttpResponse('ok')

前端html

<form>
{% csrf_token %}
{# <div>用户名:<input type="text" name="username" id="username"></div>#}
<div>选择文件:<input type="file" name="headimg" id="headimg"></div>
<div><input id="dosubmit" type="button" name="dosubmit" value="ajax上传"></div>
</form>
{# ajax上传#}
<script>
$(document).ready(function () { $("#dosubmit").click(function () {
var formdata = new FormData();
{# formdata.append("username", $("#username").val());#}
formdata.append("headimg", $("#headimg")[0].files[0]);
formdata.append("csrfmiddlewaretoken", "{{ csrf_token }}");
$.ajax({
url: "/apply/ajaxupload/",
type: "post",
data: formdata,
contentType: false,//enctype="multipart/form-data"
processData: false,//不需要转换数据类型,即不需要把传输的数据转为字符串
success: function (res) {
console.log(res)
}
}); }); })
</script>

done。

上一篇:jQuery动态创建form表单并提交到后台(携带一定的数据进行页面跳转)


下一篇:Spark大型电商项目实战-及其改良之番外(1)-将spark前端页面效果高效拷贝至博客