jiefangzhe

ajax上传图片

 

 

import os
def upload(request):
    if request.method == \'GET\':
        img_list = models.Img.objects.all()
        return render(request,\'upload.html\',{\'img_list\': img_list})
    elif request.method == "POST":
        user = request.POST.get(\'user\')
        fafafa = request.POST.get(\'fafafa\')
        obj = request.FILES.get(\'fafafa\')

        file_path = os.path.join(\'static\',\'upload\',obj.name)
        f = open(file_path, \'wb\')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()

        models.Img.objects.create(path=file_path)

        ret = {\'status\': True, \'path\': file_path}

        return HttpResponse(json.dumps(ret))

 

 

        function Uploadjq() {
            var dic = new FormData();
            dic.append(\'user\', \'v1\');
            dic.append(\'fafafa\', document.getElementById(\'img\').files[0]);

            $.ajax({
                url: \'/upload.html\',
                type: \'POST\',
                data: dic,
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                dataType: \'JSON\',
                success: function (arg) {
                    if (arg.status){
                        var img = document.createElement(\'img\');
                        img.src = "/" + arg.path;
                        $(\'#imgs\').append(img);
                    }
                }
            })

        }

 

分类:

技术点:

相关文章: