zoukankan      html  css  js  c++  java
  • django实现分片上传文件

    目标:利用django实现上传文件功能

    1,先设置路由系统

    urls.py

    from django.conf.urls import url,include
    from django.contrib import admin
    from app01 import views
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^upload/$', views.upload),
    
    ]

    2,配置html模板文件(前端页面展示)

    templates/upload.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form action="/upload/" method="post" enctype="multipart/form-data">
        <p><input type="file" name="f1"></p>
        <p><input type="text" name="hostname"></p>
        <input type="submit" value="upload">
    </form>
    </body>
    </html>

    3,开始写上传逻辑

    views.py

    
    
    #_*_ coding:utf-8 -*-
    from django.shortcuts import render,HttpResponse
    from django.views.generic.list import ListView

    def index(request):
    return HttpResponse("haha")

    def upload(request):
    if request.method == "POST": #判断接收的值是否为POST
    inp_files = request.FILES #上传文件的接收方式应该是request.FILES
    file_obj = inp_files.get('f1') #通过get方法获取upload.html页面提交过来的文件
    f = open(file_obj.name,'wb') #将客户端上传的文件保存在服务器上,一定要用wb二进制方式写入,否则文件会乱码
    for line in file_obj.chunks(): #通过chunks分片上传存储在服务器内存中,以64k为一组,循环写入到服务器中
    f.write(line)
    f.close()

    return render(request,'upload.html') #将处理好的结果通过render方式传给upload.html进行渲染

     

    4,上传功能全部完成,比较简单,我们来进行验证

    上传本地一个png的图片,然后点击upload提交

    点击提交后,在服务器上看到了刚刚上传的文件“django流程图”

    通过Django实现分片上传文件成功。

    贵有恒,何必三更起五更睡;最无益,只怕一日暴十寒
  • 相关阅读:
    苹果IPhone真机开发调试
    Unity3d 错误提示 GUI Error: You are pushing more GUIClips than you are popping. Make sure they are balanced
    Unity编辑器环境在Inspector面板中显示变量
    微信小程序开发
    Android 9.0 Http不能访问网络
    c#传不确定的参数个数,比如int型
    玩转@Git三剑客
    白话法律42讲-为程序员打造的专属法律武器
    uSurvival 1.41多人在线生存逃杀吃鸡类游戏源码
    NGUI: Next-Gen UI 2018.3.0f
  • 原文地址:https://www.cnblogs.com/rayong/p/7141507.html
Copyright © 2011-2022 走看看