1先了解以下python原生的文件保存方法:
下面这段代码没有解决上传文件重名的问题
@csrf_exempt
def upload_view(request):
if request.method == 'GET':
return render(request, 'test_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.reload() #读数据
f.write(data) #写数据
retuen HttpResponse('接收文件:' + a_file.name + '成功')
2了解文件上传之前端规则:
#前端文件上传规则:
1文件上传必须以post方式提交;
2表单< form>中文件上传时必须带有enctype="multipart/form-data"时才会包含文件内容数据
3表单中用< input type="file" name="xxx">标签上传文件
3Django后端上传文件规则:
#Django后端上传文件规则:
1视图函数中,用request.FILES取文件框的内容,例如:file=request.FILES['xxx']
说明:
1FILES的key对应页面中file框的name值
2file绑定文件流对象,
3file.name:可以拿到文件名
4file.file:可以拿到具体数据(文件的字节流数据)
3Django配置文件路径的方法:
1在setting.py中设置MEDIA相关配置,django会把用户上传的文件统称为media资源。
#file:setting.py
MEDIA_URL = '/media/' #告诉django127.0.0.1:8000/media/这个路由是哟上传文件的
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ##告诉django去哪里找资源
2MEDIA_URL和MEDIA_ROOT需要手动绑定路由
#在主路由中添加
#配置以MEDIA_URL开头的路由,Django接到该特征请求后去MEDIA_ROOT路径查找资源
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
4用Django上传文件实战:
1创建应用并添加应用:
(venv) D:\PycharmProjects\djangoProject2>python manage.py startapp upload_app
2配置setting:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'meida')
3在项目根目录创建文件夹media
右键djangoProject2--新建文件夹
4配置路由:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
5编写模型类:
class Content(models.Model):
title = models.CharField('文章名称', max_length=11)
picture = models.FileField(upload_to='picture')
6同步数据库:
(venv) D:\PycharmProjects\djangoProject2>python manage.py makemigrations
(venv) D:\PycharmProjects\djangoProject2>python manage.py migrate
7编写视图函数:
from upload_app.models import Content
@csrf_exempt
def test_upload(request):
if request.method == 'GET':
return render(request,'test_upload.html')
elif request.method == 'POST':
title = request.POST['title']
myfile = request.FILES['myfile']
Content.objects.create(title=title,picture=myfile)
return HttpResponse('--上传文件成功--')
8给视图配置url:
urlpatterns = [
path('admin/', admin.site.urls),
path('test_upload',views.test_upload),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
9访问浏览器上传图片:http://127.0.0.1:8000/test_upload
10查看数据库:
mysql> select * from upload_app_content;
+----+-----------------------+-----------------------------------------+
| id | title | picture |
+----+-----------------------+-----------------------------------------+
| 1 | 我的第一个图片 | picture/微信截图_20211204210018.png |
+----+-----------------------+-----------------------------------------+
1 row in set (0.00 sec)
mysql>
11浏览器访问图片:
http://127.0.0.1:8000/media/picture/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20211204210018.png