• django 的文件上传


    template html(模板文件):

    <form enctype="multipart/form-data" method="POST" action="/address/upload/"> 
       <input type="file" name="file" />
       <br /> 
       <input type="submit" value="上传文件" /> 
    </form>

    a、自定义上传(建议用自定义的)

    def index(request):
    if request.method == 'POST':

    obj = request.FILES.get('file')
    import os
    ppp = os.path.join('static','img',obj.name)

    f = open(ppp, 'wb')
    for chunk in obj.chunks():
    f.write(chunk)
    f.close()
    return HttpResponse(request,'上传成功')
    # return render(request, 'file.html')
    else:
    return render(request,'index.html')
                head_img = request.FILES.get('file')
                print(head_img,"我是file")
                tags = request.POST.get('tags', None)
    
    
    
                # obj = request.FILES.get('file')
                import os
                print(head_img.chunks(),"我是名字")
                Statics = os.path.dirname(os.path.dirname(__file__))
                user_img_file_path = os.path.join(Statics,"Statics",'Down_image',username)
                print(user_img_file_path)
                if not os.path.exists(user_img_file_path):
    
                    os.mkdir(user_img_file_path)
    
                img_file_path = os.path.join(user_img_file_path,head_img.name)
    
                f = open(img_file_path, 'wb')
                for chunk in head_img.chunks():
                    f.write(chunk)
                f.close()
                return HttpResponse('上传成功')
    View Code

    b、Form上传文件实例

    class FileForm(forms.Form):
        ExcelFile = forms.FileField()
    form
    from django.db import models
    
    class UploadFile(models.Model):
        userid = models.CharField(max_length = 30)
        file = models.FileField(upload_to = './upload/')
        date = models.DateTimeField(auto_now_add=True)
    models
    def UploadFile(request):
        uf = AssetForm.FileForm(request.POST,request.FILES)
        if uf.is_valid():
                upload = models.UploadFile()
                upload.userid = 1
                upload.file = uf.cleaned_data['ExcelFile']
                upload.save()
                
                print upload.file
    View Code
  • 相关阅读:
    记录一段QQ关于 UNIGUI 的Session 时间设定
    uniGUI Cannot read property 'remove' of null
    基于kbmMW Configuration Framework 实现配置文件对象化
    每日日报42
    每日日报41
    每日日报40
    解决Ajax无法跳转到其他界面
    每日日报39
    每日日报38
    《软件项目成功之道》阅读笔记01
  • 原文地址:https://www.cnblogs.com/renfanzi/p/5840077.html
Copyright © 2020-2023  润新知