上传文件
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^upload/$', views.upload_file, name='upload'),
url(r'^index/$', views.index),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .models import *
import os
# Create your views here.
def upload_file(request):
if request.method == 'GET':
return render(request,'upload_file.html')
else:
# elif request.method == 'POST':
print(request)
myFile = request.FILES.get("myfile", None)
if not myFile:
print("myFile failed.")
return HttpResponse("no file for upload!")
else:
print("myFile ok.")
# 文件路径
fp = open(os.path.join("D:\\", myFile.name), "wb+")
for chunk in myFile.chunks():
fp.write(chunk)
fp.close()
return HttpResponse('OK')
def index(request):
return HttpResponse("欢迎来到主页")
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="myfile_show" placeholder="文件名"><br>
<input type="file" name="myfile"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
注意点:
action
的字符串,一定要以’/'结尾,否则一定报错!注意了;- 在有文件上传的form表单中,method属性必须为post,而且必须指定它的
enctype="multipart/form-data"
,表明不对字符进行编码; - 注意
name
的取值,要和views.py的值保持一致,如myfile
;