• Django文件上传


    LoadFile.html中的代码如下(对应的form表单):

    <body>
    <form method="post" enctype="multipart/form-data">
    {{ uf.as_p }}
    <input type="submit" value="OK">
    </form>
    </body>

    models.py中的代码如下(对应的数据库):

    class User(models.Model):
        username = models.CharField(max_length=30)
        #在根目录下创建upload文件,上传的文件在此文件夹下
        #对应数据库中保存的是上传的文件路径        
        headImg = models.FileField(upload_to = './upload/')

    view.py中的代码如下:

    from django.shortcuts import render,render_to_response
    from django import forms
    from django.http import HttpResponse
    from models import User
    class UserForm(forms.Form):
        username = forms.CharField()
        headImg = forms.FileField()
    
    def register(req):
        if req.method == "POST":
            uf = UserForm(req.POST,req.FILES)
            if uf.is_valid():
                username = uf.cleaned_data['username']
                headImg = uf.cleaned_data['headImg']
                user = User()
                user.username = username
                user.headImg = headImg
                user.save()
                return HttpResponse("upload success")
        else:
            uf = UserForm()
        return render_to_response("LoadFile.html",{"uf":uf})
    运行项目即可看到此界面,输入名字文件名点击OK按钮即可上传成功。

  • 相关阅读:
    Java中的逆变与协变
    JAVA中使用DOM解析XML文件
    ReentrantLock的使用
    tomcat源码 Container
    tomcat源码 Connector
    tomcat源码 StandardService
    BlockingQueue队列
    tomcat源码 StandardServer
    tomcat源码 分析 Catalina
    tomcat整体架构
  • 原文地址:https://www.cnblogs.com/Yellow0-0River/p/5440719.html
Copyright © 2020-2023  润新知