2019.03.23 文件的上传下载

上传的几个注意点,post  必须写enctype = “multipart/form-data  什么文件编码的东西

主要是上传文件插入到数据库,存放的位置吧,会在本地保存的

主要还是要设置setting    input  type==file  获取请求参数的时候用request.FILES.get()

STATIC_URL = '/static/'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

#global_settings


文件上传

实现步骤

配置URL

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^student/', include('student.urls')),
]


#coding=utf-8

from django.conf.urls import url
from . import views

urlpatterns=[
  url(r'^$', views.Index.as_view()),

]

创建视图


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse

# Create your views here.



from django.views import View
class Index(View):
  def get(self,request):
      return render(request,'index.html')


  def post(self,request):
      uname = request.POST.get('uname','')
      photo = request.FILES.get('photo','')
      import os
      if not os.path.exists('static'):
          os.makedirs('static')


      with open(os.path.join(os.getcwd(),'static',photo.name),'wb') as fw:
          #一次性读取文件
          fw.write(photo.read())

      return HttpResponse('上传成功!')



创建模板



<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <form action="/student/" method="post" enctype="multipart/form-data">
      {% csrf_token %}
      用户名:<input type="text" name="uname"/><br/><br/>
      头&emsp;像:<input type="file" name="photo"/><br/><br/>
      &emsp;&emsp;&emsp;&emsp;<input type="submit" value="注册"/>

  </form>

</body>
</html>



文件下载

有意思,听懂。他的路径逻辑没看懂  哈哈哈

等博客项目做了,在弄吧

配置URL

#coding=utf-8

from django.conf.urls import url
from . import views

urlpatterns=[
  url(r'^$', views.Index.as_view()),
  url(r'^stulist/$', views.StuList.as_view()),
  url(r'^download/$', views.Download.as_view()),

]

创建视图


class Download(View):
  def get(self,request):
      #获取文件存放位置
      filepath = request.GET.get('photo','')
      #获取文件名
      filename = filepath[filepath.rindex('/')+1:]

      #获取文件绝对路径
      path = os.path.join(os.getcwd(),'media',filepath.replace('/','\\'))

      with open(path,'rb') as fr:
          response = HttpResponse(fr.read())
          response['Content-Type']='image/png'
          #预览模式
          response['Content-Disposition']='inline;filename='+filename
          #附件模式
          # response['Content-Disposition']='attachment;filename='+filename

      return response

 

文件名中文情况



from django.utils.encoding import escape_uri_path

response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file_name))

 

 
posted @ 2019-03-23 13:45  AJking  阅读(203)  评论(0编辑  收藏  举报