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('...')
  • 相关阅读:
    N!的位数
    c语言memset()函数
    通宵教室(ACM水题)
    欧拉函数+素数筛
    快速幂+大数取模
    观光浏览
    插入类排序(直接插入排序)
    showDoc使用方法
    $_POST与input('post.')区别
    “三日”面试官心得
  • 原文地址:https://www.cnblogs.com/YingLai/p/6588886.html
Copyright © 2011-2022 走看看