使用Ajax上传文件跟头像预览

使用Ajax上传文件跟图片预览

 

  • Formdata对象

      • 上传文件
1 from django.contrib import admin
2 from django.urls import path
3 from app01 import views
4 urlpatterns = [
5     path('admin/', admin.site.urls),
6     path('upload_file/', views.upload_file),
7 ]
urls.py
 1 from django.shortcuts import render,HttpResponse,redirect
 2 
 3 
 4 def upload_file(request):
 5     if request.method == "GET":
 6         return render(request,'upload_file.html')
 7 
 8     avatar = request.FILES.get('avatar')
 9     with open(avatar.name,'wb') as f:
10         for line in avatar.chunks():
11             f.write(line)
12     return HttpResponse('上传成功')
Views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
       <div style="position: relative;display: inline-block;height: 50px;min-width: 300px;overflow: hidden;">
            <div style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;z-index: 1000;border: 1px dotted #9d9d9d;color: #9d9d9d;line-height: 50px;padding-left: 15px;">
                <i class="fa fa-cloud-upload" aria-hidden="true"></i>
                <span>点击上传文件</span>
            </div>
            <input name="avatar" type="file" id="excelFile"
                   style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;background-color: #333333;z-index: 1001;opacity: 0;filter:alpha(opacity=0);">
        </div>
        <div>
{#            <input type="text" name="user">#}
            <input type="submit" value="提交">
        </div>
    </form>
    <script src="/static/js/jquery-3.2.1.min.js"></script>
<script>
{#    显示上传文件名字#}
    $(function () {
        $('#excelFile').change(function (e) {
            var fileName = e.currentTarget.files[0].name;
            $(this).prev().find('span').text(fileName);
        })
    })
</script>
</body>
</html>
upload_file.html
      • 上传以及预览图片(预览图片的本质就是更改图片的src
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('upload_img/', views.upload_img),
    path('form_data_upload/', views.form_data_upload)
]
urls.py
import os
import uuid
from django.shortcuts import render,HttpResponse,redirect

def upload_img(request):
    if request.method == "GET":
        return render(request,'upload_img.html')
    user = request.POST.get('user')
    avatar = request.POST.get('avatar')
    print(user,avatar)
    return HttpResponse('上传成功')

#-------------------------------------------
def form_data_upload(request):
    """
    ajax上传文件
    :param request:
    :return:
    """
    img_upload = request.FILES.get('img_upload')

    file_name = str(uuid.uuid4()) + "." + img_upload.name.rsplit('.', maxsplit=1)[1]
    img_file_path = os.path.join('static', 'imgs', file_name)
    # 将上传的文件对象写到服务器,并将文件的地址返回给ajax请求。
    with open(img_file_path, 'wb') as f:
        for line in img_upload.chunks():
            f.write(line)

    return HttpResponse(img_file_path)
Views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div style="height: 100px;width: 100px;padding: 2px;border: 1px solid #dddddd;position: relative;">
    <img style="height: 100%;width: 100%;border: 0;overflow: hidden;border-radius: 50%;"
         id="previewImg"
         src="/static/imgs/default.png">
    <input style="top: 0;left: 0;right: 0;bottom: 0;opacity: 0;position: absolute;z-index: 102;" id="avatarImg"
           name="avatar_img" type="file" class="img-file"/>
</div>
<div>点击图片更换(<a href="#">撤销</a>)</div>

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <div>
        <input type="text" name="avatar" id="avatar">
        <input type="text" name="user">
        <input type="submit" value="提交">
    </div>
</form>
<script src="/static/js/jquery-3.2.1.min.js"></script>
    <script>
        $(function () {
            bindChangeAvatar3();
        });

        function bindChangeAvatar3() {
   {% comment %}选定目标文件确定时触发函数,发送ajax请求到"/form_date_upload/",
                拿到图片地址作为返回值,用dom修改图片src达到预览效果{% endcomment %}
            $('#avatarImg').change(function () {
                var file_obj = $(this)[0].files[0];
                var form = new FormData();
                form.append('img_upload', file_obj);
                $.ajax({
                    url: '/form_data_upload/',
                    type:'POST',
                    data: form,
                    processData: false,  // tell jQuery not to process the data
                    contentType: false,  // tell jQuery not to set contentType
                    success: function (arg) {
                        // 给img标签设置src属性,实现预览效果
                        $('#previewImg').attr('src',"/"+arg);
                        $('#avatar').val("/"+arg);
                    }
                })
            })
        }
    </script>
</body>
</html>
upload_img.html
  • iframe预览图片
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('iframe_upload_img/', views.iframe_upload_img),
    path('upload_iframe/', views.upload_iframe),

]
urls.py
import json
from django.shortcuts import render,HttpResponse,redirect


USER_LIST = []

def index(request):
    return render(request,'index.html',{'user_list':USER_LIST})

def iframe_upload_img(request):
    if request.method == "GET":
        return render(request,'iframe_upload_img.html')
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    avatar = request.POST.get('avatar')
    USER_LIST.append(
        {
            'user':user,
            'pwd':pwd,
            'avatar':avatar
        }
    )
#对常规的form表单数据进行处理
    return redirect('/index/')

#*********************************

def upload_iframe(request):
    ret = {'status':True,'data':None}
    try:
        avatar = request.FILES.get('avatar')
        file_name = str(uuid.uuid4()) + "." + avatar.name.rsplit('.', maxsplit=1)[1]
        img_file_path = os.path.join('static', 'imgs', file_name)
        with open(img_file_path, 'wb') as f:
            for line in avatar.chunks():
                f.write(line)
        ret['data'] = os.path.join("/",img_file_path)
    except Exception as e:
        ret['status'] = False
        ret['error'] = '上传失败'
    return HttpResponse(json.dumps(ret))

#对与iframe组合的form表单进行处理。返回的值显示在iframe里面。
在前端通过 “var iframeContents = $('#ifr')[0].contentWindow.document.body.innerText;”获取返回值
Views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
     <div style="height: 100px;width: 100px;padding: 2px;border: 1px solid #dddddd;position: relative;">
            <iframe style="display: none;" id="ifr" name="fffff"></iframe>
            <form method="POST" action="/upload_iframe/" enctype="multipart/form-data" target="fffff">
                {% csrf_token %}
                <img style="height: 100px;width: 100px;border: 0;overflow: hidden;border-radius: 50%;" id="prevImg"
                     src="/static/imgs/default.png">
                <input style="top: 0;left: 0;right: 0;bottom: 0;opacity: 0;position: absolute;z-index: 102;"
                       id="avatar"
                       name="avatar" type="file" class="img-file"/>
            </form>
        </div>

     <form method="post" action="/iframe_upload_img/">
         {% csrf_token %}
         <input type="text" name="avatar" id="formAvatar" style="display: none">
         <input type="text" name="user" placeholder="请输入用户名">
         <input type="text" name="pwd" placeholder="请输入密码">
         <input type="submit" value="提交">
     </form>

    <script src="/static/js/jquery-3.2.1.min.js"></script>
    <script>
        $(function () {
            bindChangeAvatar4();
        });

         function bindChangeAvatar4() {
            $('#avatar').change(function () {
                $(this).parent().submit();
                // {#提交form表单#}
                $('#ifr')[0].onload = function (){
                    var iframeContents = $('#ifr')[0].contentWindow.document.body.innerText;
##获取与iframe标签组合的form表单返回值
                    iframeContents = JSON.parse(iframeContents);反序列化
                    if (iframeContents.status) {
                        $('#prevImg').attr('src', iframeContents.data);
                        $('#formAvatar').val(iframeContents.data);
            #将返回值赋值到常规form表单中,将值传到后端。
                    }
                }

            })
        }

    </script>
</body>
</html>        
iframe_upload_img.html

 

  • CreateObjectURL对象
      • 上传预览图片(只在浏览器端实现,不涉及后端)  
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('upload_img/', views.upload_img),
]
urls.py
def upload_img(request):
    if request.method == "GET":
        return render(request,'upload_img.html')
Views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <div style="height: 100px;width: 100px;padding: 2px;border: 1px solid #dddddd;position: relative;">
        <img style="height: 100%;width: 100%;border: 0;overflow: hidden;border-radius: 50%;"
             id="previewImg"
             src="/static/imgs/default.png">
        <input style="top: 0;left: 0;right: 0;bottom: 0;opacity: 0;position: absolute;z-index: 102;" id="avatarImg"
               name="avatar_img" type="file" class="img-file"/>
    </div>
    <div>点击图片更换(<a href="#">撤销</a>)</div>

    <div>
        <input type="text" name="user">
        <input type="submit" value="提交">
    </div>
</form>
<script src="/static/js/jquery-3.2.1.min.js"></script>
<script>
    $(function () {
        bindChangeAvatar1();
    });

    function bindChangeAvatar1() {
        $('#avatarImg').change(function () {
            var file_obj = $(this)[0].files[0];
            var blob = window.URL.createObjectURL(file_obj);
            document.getElementById('previewImg').src = blob;

            $('#previewImg').load(function () {
                window.URL.revokeObjectURL(blob);
            })
        })
    }
</script>
</body>
</html>
upload_img.html
  • FileReader对象
      • 预览图片(只在浏览器端实现,不涉及后端)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <div style="height: 100px;width: 100px;padding: 2px;border: 1px solid #dddddd;position: relative;">
        <img style="height: 100%;width: 100%;border: 0;overflow: hidden;border-radius: 50%;"
             id="previewImg"
             src="/static/imgs/default.png">
        <input style="top: 0;left: 0;right: 0;bottom: 0;opacity: 0;position: absolute;z-index: 102;" id="avatarImg"
               name="avatar_img" type="file" class="img-file"/>
    </div>
    <div>点击图片更换(<a href="#">撤销</a>)</div>

    <div>
        <input type="text" name="user">
        <input type="submit" value="提交">
    </div>
</form>
<script src="/static/js/jquery-3.2.1.min.js"></script>
<script>
    $(function () {
        bindChangeAvatar2();
    });
    function bindChangeAvatar2() {
        $('#avatarImg').change(function () {
            var file_obj = $(this)[0].files[0];
            var reader = new FileReader();
            reader.readAsDataURL(file_obj);
            reader.onload = function (e) {
                $('#previewImg')[0].src = this.result;
            };
        })
    }
</script>
</body>
</html>
upload_img.html

 

    

     

 

    

    

 

posted on 2018-07-21 15:50  弃疾  阅读(124)  评论(0)    收藏  举报

导航