zoukankan      html  css  js  c++  java
  • django 基于form表单上传文件和基于ajax上传文件

    一、基于form表单上传文件

    1、html里是有一个input type="file" 和 ‘submit’的标签

    2、vies.py

    def fileupload(request):
        if request.method == 'POST':
            print(request.POST)
            print(request.FILES)
            # from django.core.files.uploadedfile import InMemoryUploadedFile
            print(type(request.FILES.get('myfile')))
            myfile = request.FILES.get('myfile')
            name = myfile.name
            print(name)
            with open(name,'wb') as f:
                # for line in myfile.chunks():
                #     f.write(line)
                for line in myfile:
                    f.write(line)
            return HttpResponse('文件上传成功')

    二、基于JSON上传文件

     $("#ajax_button").click(function () {
            var formdata=new FormData()
            formdata.append('name',$("#id_name2").val())
            formdata.append('myfile',$("#myfile")[0].files[0])
            $.ajax({
                url:'',
                type:'post',
                processData:false, //告诉jQuery不要去处理发送的数据
                contentType:false,// 告诉jQuery不要去设置Content-Type请求头
                data:formdata,
                success:function (data) {
                    console.log(data)
    
                }
    
            })
        })
    def fileupload(request):
        if request.method == 'POST':
            print(request.POST)
            print(request.FILES)
            # from django.core.files.uploadedfile import InMemoryUploadedFile
            print(type(request.FILES.get('myfile')))
            myfile = request.FILES.get('myfile')
            name = myfile.name
            print(name)
            with open(name,'wb') as f:
                # for line in myfile.chunks():
                #     f.write(line)
                for line in myfile:
                    f.write(line)
            return HttpResponse('文件上传成功')

    三、综上所述

      基于form表单上传文件和基于ajax上传文件后端view界面一样的不需要改动,前台需呀改动

  • 相关阅读:
    Windows32位与64位操作系统的区别【转】
    【C#多线程详解】
    auto_ptr
    #if 1......
    vector 向量容器
    删除可视图中的类不能彻底避免它重新被编译
    _tWinMain 与wWinMain 区别
    explicit 用法
    转:atoi函数的实现
    string类的实现
  • 原文地址:https://www.cnblogs.com/di2wu/p/10068511.html
Copyright © 2011-2022 走看看