Django中添加文件上传功能

创建一个应用

python3 manage.py startapp sandbox

sandbox

创建文件夹

sandbox目录下创建一个templates目录, 为了规范再在templates目录创建一个和应用同名的目录sandbox, 然后在创建一个upload.html文件;
在这里插入图片描述
upload.html文件主要内容如下:

	<form id="filesub" action="/upload" method="post" enctype="multipart/form-data">
	    {% csrf_token %}
	    <input type="file" id="file-uploader" name="userfile">
	</form>
	<script>
	    document.getElementById("file-uploader").onchange = function () {
	        document.getElementById("filesub").submit();
	    };
	</script>

当打开文件后可以直接自动上传;

sandbox/views.py 处理函数

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_ROOT = os.path.join(BASE_DIR, 'static\\upfile')
def upload(request):
    if request.method == "GET":
        return render(request, 'sandbox/upload.html')
    if request.method == 'POST':
        # 获取对象
        obj = request.FILES.get('userfile')
        # 上传文件的文件名     
        print(obj.name)
        f = open(os.path.join(BASE_DIR, 'sandbox', 'static', 'upfile', obj.name), 'wb')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()
        return HttpResponse("OK")

配置路由

在项目下/项目文件/url.py中:
x

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('sandbox.urls')),
]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值