django文件上传

首先配置settings.py文件,定义文件上传资料夹名称和路径

STATIC_URL = '/static/'
STATICFILES_DIRS=[
    os.path.join(BASE_DIR,"static")
]

MEDIA_ROOT=[
    os.path.join(BASE_DIR,"upload")
]
MEDIA_URL="/upload/"

前端HTML页面

<form action="/fileUpload.html" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <p>username: <input type="text" name="username"></p>
    <p><input type="file" name="file"></p>
    <p><input type="submit" value="上传"></p>
</form>

Views内容,这里使用的Form组件验证,但是没写内容,注意文件上传路径及文件名称,可以自行更改

from django.shortcuts import render,HttpResponse
from django import forms

#增加图片上传Form验证
class fileForm(forms.Form):
    username = forms.CharField(
        min_length=2,
        error_messages={"min_lenth":"名字长度不够"}
    )
    file = forms.FileField(
    )

# Create your views here.
def fileUpload(request):
    if request.method=="GET":
        return render(request,"fileupload.html")
    elif request.method=="POST":
        obj = fileForm(request.POST,request.FILES)
        if obj.is_valid():
            username=obj.cleaned_data["username"]
            file = obj.cleaned_data["file"]
            newfile = open("upload/"+file.name,"wb")
            for item in file.chunks():
                newfile.write(item)
            newfile.close()
            print(file.name,file.size,"ok")
            return HttpResponse("OK1111")
        else:
            print("NG")
            return HttpResponse("NG1111")
    else:
        print("hahaha")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值