Django实现
form表单实现文件的上传
/form_upload/urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^upload/', views.upload),
]
/app01/views.py
from django.shortcuts import render
import os
from django.conf import settings
import datetime
# Create your views here.
def upload(request):
# 1. 第一次GET请求来, 应该给用户返回一个页面
if request.method == 'POST':
# print(request.FILES)
file_obj = request.FILES.get('file_name') # 文件对象
# print(type(file_obj)) # <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
# print(type(file_obj.name)) # <class 'str'>
file_name = file_obj.name
if os.path.exists(os.path.join(settings.BASE_DIR, file_name)):
# 如果存在重名的文件
name, suffix = file_name.split('.')
datatime_obj = datetime.datetime.now()
year, month, day, hour, minute,second = datatime_obj.year, datatime_obj.month, datatime_obj.day,datatime_obj.hour, datatime_obj.minute, datatime_obj.second
name += '_%s-%s-%s %s:%s:%s'%(year, month, day, hour, minute, second)
file_name = '%s.%s'%(name, suffix)
# 从上传文件对象里 一点一点读取数据, 写到本地
# with open(file_obj.name, 'wb') as f:
# for line in file_obj:
# f.write(line)
# 官方推荐写法, file_obj.chunks() 可以指定一次读多少数据
with open(file_name, 'wb') as f:
for chunk in file_obj.chunks(2200):
f.write(chunk)
return render(request, 'upload.html')