1、前端基礎
1.form表單上傳文件必須使用post方式,設置method="post"
2.form表單上傳文件時,需要設置enctype="multipart/form-data"
2、form表單設置
<!--使用bootstrap樣式-->
<form class="form-horizontal" method="post" action="/commodityAdd/" enctype="multipart/form-data">
<div class="form-group">
<label for="inputImage" class="col-sm-2 control-label">標志圖片</label>
<div class="col-sm-10">
<input type="file" name="commodityImage" id="inputImage">
<p class="help-block">請傳入800X800圖片.</p>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger">提 交</button>
</div>
</form>
3、Django后台接收文件
1.request.FILES ---->存放所有文件的大字典
2.request.FILES.get("commodityImage",None) ---->獲取form表單中name="commodityImage"的文件輸入框中上傳的文件
def commodityAdd(request):
#獲取圖片,此時該文件格式為二進制 commodity_image = request.FILES.get("commodityImage", None)
#使用二進制的方式打開新建文件,不改變文件,直接寫入
with open("picture.jpg",mode="wb") as image_file:
for content in commodity_image: image_file.write(content) return render(request, "commodityAdd.html")