16.Django learning file upload and download

Upload so six steps!

One,

settings configuration file is

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'medias').replace('\\', '/')#media即为图片上传的根路径

two,

url routing configuration

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index,name='index'),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #如果单纯的是上传,文件并不用来显示或者读取,就不用加这个

three,

models.py file written

class Book(models.Model):

    name = models.CharField(max_length=32)
    date1 = models.DateTimeField(auto_now=True,null=True)
    date2 = models.DateTimeField(auto_now_add=True,null=True)
    img = models.ImageField(upload_to='img',null=True) #写上upload_to,后面指定一个路径,那么将来上传的文件会直接生成到配置文件中的那个medias文件夹中的img文件夹中,不需要我们自己写读取文件内容写入本地文件的操作,django内部帮我们自动处理了

four,

views view function in the wording, upload a picture:

def index(request):

    if request.method == 'POST':
        print(request.POST)
        username = request.POST.get('username')
        print('files',request.FILES)
        file_obj = request.FILES.get('file')
        models.Book.objects.create(
            name=username,
            img=file_obj,
        )  #自动就会将文件上传到我们配置的img文件夹中
        return render(request,'index.html')

Fives,

Updated uploaded files (note that only updates the path stored in the database file that field, but previously uploaded files are not automatically deleted, we need to upload their own fault before the write logic to delete or need to be covered file. If there is upload the file name is the same then you will find the path behind in this field in the database file name will appear from a random string of eight random bad, because the file name conflicts upload, django to resolve this conflict, you change the look of your file name.)

obj = models.Book.objects.get(name='chao2')
obj.img=file_obj
obj.save()

#下面的update方法是不能更新正确更新保存的文件路径的,除非我们自己手动拼接文件路径,然后img=路径来进行update更新
models.Book.objects.filter(name='chao2').update(img=file_obj)

six,

View already uploaded files (we will need the help of the above settings in the configuration file and the url configuration)

views.py view function wording:

def index(request):
        objs = models.Book.objects.all()
        return render(request,'index.html',{'objs':objs})

index.html file in writing:

<div>
    {% for obj in objs %}
        <img src="/media/{{ obj.img }}" alt="">
    {% endfor %}

</div>
<div>
    {% for obj in objs %}
        <img src="/media/{{ obj.img }}" alt="">
        <!--<img src="/media/{{ obj.img.name }}" alt="">-->
    {% endfor %}

</div>

download

In actual projects often you need to use the download function, such as guide excel, pdf file or download, of course, you can use the service to build their own web server resources can be used to download, such as nginx, here we introduce the downloaded file in django .

Here we introduce three kinds of writing simple Django download the file, and then use a third way to complete a number of advanced file download methods

index.html follows

<div>
    <a href="{% url 'download' %}">文件下载</a>
</div>

urls.py document reads as follows:

urlpatterns = [

    url(r'^index/', views.index,name='index'),
    url(r'^download/', views.download,name='download'),

]

View view function has written about in three ways:

Mode 1:

from django.shortcuts import HttpResponse
def download(request):
  file = open('crm/models.py', 'rb') #打开指定的文件
  response = HttpResponse(file)   #将文件句柄给HttpResponse对象
  response['Content-Type'] = 'application/octet-stream' #设置头信息,告诉浏览器这是个文件
  response['Content-Disposition'] = 'attachment;filename="models.py"' #这是文件的简单描述,注意写法就是这个固定的写法
  return response

  Note: HttpResponse directly using an iterator object, content storage City String iterator object, and then returned to the client, while freeing memory. When larger files can see that this is a very time consuming process and memory. And StreamingHttpResponse content file is streamed, data volume can use this method

Option 2:

from django.http import StreamingHttpResponse #
def download(request):
  file=open('crm/models.py','rb')
  response =StreamingHttpResponse(file)
  response['Content-Type']='application/octet-stream'
  response['Content-Disposition']='attachment;filename="models.py"'
  return response

Mode 3:

from django.http import FileResponse
def download(request):
  file=open('crm/models.py','rb')
  response =FileResponse(file)
  response['Content-Type']='application/octet-stream'
  response['Content-Disposition']='attachment;filename="models.py"'
  return response

Three kinds

Three kinds of http response object in django official website has introduced entrance:. Https://docs.djangoproject.com/en/1.11/ref/request-response/

FileResponse recommended, from the source can be seen FileResponse be StreamingHttpResponse subclass iterator internal data streaming.

Guess you like

Origin www.cnblogs.com/changxin7/p/12026953.html