zoukankan      html  css  js  c++  java
  • Django之文件上传


    #示例一
    #
    views def upload(request): if request.method == "GET": return render(request, "upload.html") elif request.method == "POST": name = request.POST.get("user") img = request.FILES.get("img") print("用户名", name) print("文件名", img.name) print("文件大小", img.size) f = open(img.name, "wb") for line in img.chunks(): f.write(line) f.close() return HttpResponse("...") # 前端 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload.html" method="post" enctype="multipart/form-data"> <input type="text" name="user"> <input type="file" name="img"> <input type="submit" value="提交"> </form> </body> </html>

     示例二:( form组件)

    from django.shortcuts import render
    from django.shortcuts import HttpResponse
    
    from django import forms
    from django.forms import fields
    class UploadForm(forms.Form):
        user = fields.CharField()
        img = fields.FileField()
    def upload(request):
        if request.method == 'GET':
            return render(request,'upload.html')
        else:
             obj = UploadForm(request.POST,request.FILES)
              if obj.is_valid():
                 user = obj.cleaned_data['user']
                 img = obj.cleaned_data['img']
           
            # img是对象(文件大小,文件名称,文件内容。。。)
            print(img.name)
            print(img.size)
            f = open(img.name,'wb')
            for line in img.chunks():
                f.write(line)
            f.close()
            return HttpResponse('...')
  • 相关阅读:
    从Delegate.CreateDelegate看值类型的实例方法
    c#编译器如何处理匿名委托
    线程静态的几个特点
    Framework 3.5学习笔记
    看看给我用的基类,还有多少人愿意做下去
    .net里面数组的复制
    装饰模式与大接口的装饰模式的思考
    SingleTon的实现与性能
    特性与方法注入
    CLR与浮点数
  • 原文地址:https://www.cnblogs.com/YingLai/p/6588886.html
Copyright © 2011-2022 走看看