django 文件上传(阿里云oss)下载(支持大文件下载)
1.文件上传
Models 设计
class Upload_File(models.Model): image = models.FileField(upload_to='file/%Y/%m',default = 'image/default.png',max_length=100) add_time = models.DateTimeField(auto_now_add=True,verbose_name='添加时间')
forms 设计
from django import forms from .models import Upload_File class UploadFileForm(forms.ModelForm): class Meta: model = Upload_File fields = ['image']
settings设计
STATIC_URL = '/static/' MEDIA_URL = '/media/' #文件上传目录 MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #文件上传地址
View设计(上传思路:先保存到本地media目录然后读取目录,保存到云服务器,方法比较笨,但是能实现后期优化)
#阿里云OSS的基本配置 access_key_id = os.getenv('OSS_TEST_ACCESS_KEY_ID', 'LLLLLLLLLL') access_key_secret = os.getenv('OSS_TEST_ACCESS_KEY_SECRET', 'BBBBBB') bucket_name = os.getenv('OSS_TEST_BUCKET', 'CCCCC') endpoint = os.getenv('OSS_TEST_ENDPOINT', 'https://oss-cn-beijing.aliyuncs.com') # 确认上面的参数都填写正确了 for param in (access_key_id, access_key_secret, bucket_name, endpoint): assert '<' not in param, '请设置参数:' + param # 创建Bucket对象,所有Object相关的接口都可以通过Bucket对象来进行 def GetForm(request): """ 请求表单 """ file = Upload_File() if request.method == 'POST': Up_File = UploadFileForm(request.POST, request.FILES) if Up_File.is_valid(): headFile = Up_File.cleaned_data['image'] file.image = headFile print(MEDIA_ROOT) file.save() print(file.image.name) print(file.image.path) bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name) bucket.put_object_from_file('{}/{}'.format('media', file.image.name),'{}/{}'.format('media', file.image.name)) # # 下载到本地文件 # bucket.get_object_to_file('media/file/2018/01/1曾经有一份真挚的爱情大话西游经典片段.mp4', 'media/file/2018/01/1曾经有一份真挚的爱情大话西游经典片段.mp4') return HttpResponse('{"status":"success"}', content_type='application/json')
URL设计
from django.views.static import serve #用于处理上传文件 from django_upload.settings import MEDIA_ROOT # 上传文件 url(r'^form/$', GetForm, name='go_form'), # 配置上传文件的访问函数 url(r'^media/(?P<path>.*)$', serve, {'document_root': MEDIA_ROOT}),
HTML
<form action="{% url 'go_form' %}" method="post" enctype="multipart/form-data" class="smart-green"> <span class="fl upload-inp-box" style="margin-left:70px;"> <input type="file" name="image" id="avatarUp" class="js-img-up"/> </span> <label> <span> </span> <br><br><br> <input type="submit" class="button" value="提交"/> <br><br> </label> {% csrf_token %} </form>
2.文件下载:
View
def file_down(request): """ 文件下载 """ def readFile(fn, buf_size=262144): f = open(fn, "rb") while True: c = f.read(buf_size) if c: yield c else: break f.close() path = os.path.abspath(MEDIA_ROOT) print(path)
#文件相对路径 path = 'media/file/2018/01/遥领医疗数据AI项目商业计划书-20171211.pptx' print(path) response = StreamingHttpResponse(readFile(path)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=%s' % (urlquote('遥领医疗数据AI项目商业计划书-20171211.pptx')) #下载后的名字 return response
url设计
#文件下载 url(r'^file_down/$', file_down, name='file_down'),
HTML
<button> <a href="/file_down/">下载</a> </button>