Python Django文件上传

文件保存本地

view视图

def update(request):
    if request.method =='GET':
        return render(request,'update.html')
    else:
        myFile = request.FILES.get("img")
    #上传的文件是一个对象
        print(myFile.name)
        print(myFile.size)
        f = open(myFile.name,'wb')
        for files in myFile.chunks():
            f.write(files)
        return render(request,'update.html')

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="update.html" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    文件上传:<input type="file" name="img">
    <input type="submit">
</form>

</body>
</html>

文件上传到数据库

首先 需要在setting中设置文件的存储路径 

#一般创建static文件
MEDIA_ROOT = os.path.join(BASE_DIR,"static/...")
#在models中创建数据库
class Files(models.Model):
    photo_url = models.ImageField(
        upload_to='imgae'
    )

view视图
def files_ulr(request):
if request.method =='GET':
return render(request,'photo.html')
else:
myFile = request.FILES.get('img')
photo_url = models.Files.objects.create(photo_url=myFile)
return HttpResponse("ok")

通过Ajax上传文件

 

#HTML中编辑JQ语句
form action="update.html" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    头像<input type="file" name="touxiang" id="file">
    <br>
    <button id="btn">提交</button>
</form>
<script>
    $("#btn").click(function(){
        {#ajax上传文件的时候需要这个类型,它会将添加的键值对加工成formata的类型#}
        var formdata = new FormData();
        {##添加键值对的方法是append,注意写法,键和值之间使用逗号隔开#}
        formdata.append('file',$("#file")[0].files[0]);
        {#csrf_tocken#}
        formdata.append('csrfmiddlewaretoken',$('[name=csrfmiddlewaretoken]').val());
        console.log(formdata)
        $.ajax({
            'url':'update.html',
            'type':'post',
            'data':formdata,
            {#不处理数据#}
            processData:false,
            contentType:false,
            success:function(arg){
                console.log(arg)
            }
        })
    })
</script>
#view中操作
    if request.method =='GET':
        return render(request,'update.html')
    else:
        # name = request.POST.get('uname')
        file = request.FILES.get('touxiang')
        file_name = file.name
        # 拼接文件路径
        # path = os.path.join('static','img',file_name)
        with open(file_name,'wb') as f:
            for i in file.chunks():
                f.write(i)
        return render(request, 'update.html')

 

  

 

posted @ 2020-02-27 17:12  Mr.toby  阅读(257)  评论(0编辑  收藏  举报