## 文件上传
- 文件上传必须为POST提交方式
- 表单`<form>`中文件上传时必须有带有`enctype="multipart/form-data"` 时才会包含文件内容数据。
- 表单中用`<input type="file" name="xxx">`标签上传文件
- 名字`xxx`对应`request.FILES[‘xxx‘]` 对应的内存缓冲文件流对象。可通能过`request.FILES[‘xxx‘]` 返回的对象获取上传文件数据
- `file=request.FILES[‘xxx‘]` file 绑定文件流对象,可以通过文件流对象的如下信息获取文件数据
file.name 文件名
file.file 文件的字节流数据
- 上传文件的表单书写方式
```html
<!-- file: index/templates/index/upload.html -->
<html>
<head>
<meta charset="utf-8">
<title>文件上传</title>
</head>
<body>
<h3>上传文件</h3>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="myfile"/><br>
<input type="submit" value="上传">
</form>
</body>
</html>
```
- 在setting.py 中设置一个变量MEDIA_ROOT 用来记录上传文件的位置
```python
# file : settings.py
...
MEDIA_ROOT = os.path.join(BASE_DIR, ‘static/files‘)
```
- 在当前项目文件夹下创建 `static/files` 文件夹
```shell
$ mkdir -p static/files
```
- 添加路由及对应的处理函数
```python
# file urls.py
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^upload‘, views.upload_view)
]
```
- 上传文件的视图处理函数
```python
# file views.py
from django.http import HttpResponse, Http404
from django.conf import settings
import os
def upload_view(request):
if request.method == ‘GET‘:
return render(request, ‘index/upload.html‘)
elif request.method == "POST":
a_file = request.FILES[‘myfile‘]
print("上传文件名是:", a_file.name)
filename =os.path.join(settings.MEDIA_ROOT, a_file.name)
with open(filename, ‘wb‘) as f:
data = a_file.file.read()
f.write(data)
return HttpResponse("接收文件:" + a_file.name + "成功")
raise Http404
```
原文:https://www.cnblogs.com/chenlulu1122/p/11980744.html