html tool

2021年7月8日星期四

Django简单上传文件例子

 URL :

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from hW import views

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

 

前端代码 :

<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="file">
    <input type="submit">
</form>

 

视图代码 :

import os
from django.conf import settings
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def upload(request):
    c={}
    if request.method == "POST":
        filename = request.FILES["file"].name
        if os.path.exists(os.path.join(settings.BASE_DIR, filename)):
            name, suffix = filename.split(".")
            name += "1"
            filename = name + "." +suffix
        with open(filename, "ab") as f:
            for chunk in request.FILES["file"].chunks():
                f.write(chunk)
        return HttpResponse("OK")
    return render(request, "file.html", c)

 

没有评论:

发表评论