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('...')
  • 相关阅读:
    个人期末总结
    团队冲刺第二阶段10
    团队冲刺第二阶段9
    团队冲刺第二阶段8
    团队冲刺第二阶段7
    团队冲刺第二阶段6
    数据分析之例题
    数据分析之数据操作
    数据分析之Matplotlib可视化
    数据分析之Pandas
  • 原文地址:https://www.cnblogs.com/YingLai/p/6588886.html
Copyright © 2011-2022 走看看