form表單文件上傳 路由 方法 前端html 上傳成功示例 #ajax上傳 路由 方法 前端html done。 ...
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>
上傳成功示例
#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。