ajax transfer files

ajax transfer files

Ajax file transfer issues should be noted

1, objects can simply use formdata fast front-end data transfer (+ general key files) from, this is the Ajax advantage. No separate pass.

2, there are several parameters:

1.data:formdata objects

​ 2.contentType:false

​ 3.processData:false

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
      <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>

</head>
<body>
<input type="text" name="username" id="t1">
<input type="text" name="password" id="t2">
<input type="file" name="myfile" id="t3">
<button id="b1">提交</button>

<script>
    $('#b1').click(function () {
        // 1.先生成一个formdata对象
        var myFormData = new FormData();
        // 2.朝对象中添加普通的键值
        myFormData.append('username',$("#t1").val());
        myFormData.append('password',$("#t2").val());
        // 3.朝对象中添加文件数据
        // 1.先通过jquery查找到该标签
        // 2.将jquery对象转换成原生的js对象
        // 3.利用原生js对象的方法 直接获取文件内容
        myFormData.append('myfile',$('#t3')[0].files[0]);
        $.ajax({
            url:'',
            type:'post',
            data:myFormData,  // 直接丢对象
            // ajax传文件 一定要指定两个关键性的参数
            contentType:false,  // 不用任何编码 因为formdata对象自带编码 django能够识别该对象
            processData:false,  // 告诉浏览器不要处理我的数据 直接发就行
            success:function (data) {
                alert(data)
            }
        })
    })
</script>

</body>

</html>

Here to talk about their stupid stepped pit:

Since a file sent over, and I'll persistent store it. My mind began to think about how to save the file, read the relevant knowledge documents found empty!

def upload(request):
    files = request.FILES.get('myfile')

    print(request.FILES)
    if request.is_ajax():
        if request.method == 'POST':
            print(request.POST)
            with open(r'D:\python\untitled\上课\day62\file_download\hahaha'+'.py','wb')as fw:
                for f in files:
                    fw.write(f)
            return HttpResponse('收到了 dsb')

    return render(request,'upload.html')

To remind myself about, read documents, must file instead of something like a folder, file write, file path if it does not exist, he would create a file themselves, if the file exists, it will be overwritten!

And the most important point is that, request.FILES not directly to our file, but a

<Class 'django.utils.datastructures.MultiValueDict'> dictionary, I do not know what is, in short, we need to get out. Then is the type of binary files.

Serialization assembly

We went to the front-end data transfer, query directly from the database out of a lot of objects, then threw the preceding paragraph, himself the front-end, which is supported by django, but taking into account the future development, the front will not necessarily be compatible with you, so this time we are going to use compatible data format, json.

So we have to be written in the form of a list of sets of dictionaries to pass front-end, but by hand will become very cumbersome, so there is still a relatively low module, but better than handwriting.

He is not just a sequence of only the dumps.

from app01 import models
from django.core import serializers #这个模块用来序列化
def ser(request):
    user_queryset = models.Userinfo.objects.all()
    res = serializers.serialize('json',user_queryset)#前一个参数告诉这个方法要序列化成什么类型的数据,后面的参数就是你要序列化的数据。
    print(res)
    return render(request,'ser.html',locals())
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
      <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>

</head>
<body>
{{ res }}
</body>
</html>

Anterior file

[{
    "model": "app01.userinfo",
    "pk": 1,
    "fields": {
        "username": "chanyuli",
        "password": 123,
        "gender": 1
    }
}, {
    "model": "app01.userinfo",
    "pk": 2,
    "fields": {
        "username": "tank",
        "password": 321,
        "gender": 1
    }
}, {
    "model": "app01.userinfo",
    "pk": 3,
    "fields": {
        "username": "ax",
        "password": 720,
        "gender": 2
    }
}]

These are the pre-stage the received data after checking json formatting tools (bejson) the formatted data.

Guess you like

Origin www.cnblogs.com/chanyuli/p/11761421.html