码迷,mamicode.com
首页 > Web开发 > 详细

文件上传及图片预览

时间:2018-07-18 21:38:54      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:class   method   pwd   his   覆盖   formdata   with   line   position   

文件上传:

  第一种方式:

  python:

def upload_file(request):
    if request.method == "GET":
        return render(request,"upload_file.html")
    user = request.POST.get("user")
    avatar = request.FILES.get("customer_excel") # 获取文件对象
    with open(avatar.name,"wb") as f:
        for line in avatar.chunks():  # chunks():分块,写不写都一样。
            f.write(line)
    return HttpResponse("上传成功")

  html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" 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="customer_excel" 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/plugins/jquery.js"></script>
<script>
    $(function(){
        $("#excelFile").change(function (e) {
            var fileName = e.currentTarget.files[0].name;
            console.log(fileName);
            $(this).prev().find("span").text(fileName);
        })
    })
</script>
</body>
</html>

  2,利用ajax上传图片及预览

  python:

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("上传成功")

import os
import uuid
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(".",1)[1]
    # 将文件的格式切出来,并利用uuid生成随机字符串再重新组成名字,为了使每个传入的文件名字不相同,避免被覆盖
    img_file_path = os.path.join("static","img",file_name)  # 拼出一个路径
    with open(img_file_path,"wb") as f:
        for line in img_upload.chunks():
            f.write(line)
    print(img_file_path)
    return HttpResponse(img_file_path)

  html:

<!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/img/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/plugins/jquery.js"></script>
<script>
    $(function () {
        bindChangeAvatar3();
    });
    function bindChangeAvatar3() {
        $("#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 (data) {
                    //给 img 标签设置src属性,预览
                    console.log(data);
                    $("#previewImg").attr("src","/"+data); //预览图片,给图片赋予src地址
                    $("#avatar").val("/"+data);  //将图片的地址
                }
            })
        })
    }
</script>
</body>
</html>

  3,利用iframe 创建一个伪AJAX上传预览:

  python:

import json
def upload_iframe(request):
    ret = {"status":True,"data":None}
    try:
        avatar = request.FILES.get("avatar")
        file_name = str(uuid.uuid4())+ "." + avatar.name.rsplit(".",1)[1]
        img_file_path = os.path.join("static","img",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))

  html:

<!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();
                $(#ifr)[0].onload = function (){
                    var iframeContents = $(#ifr)[0].contentWindow.document.body.innerText;
                    iframeContents = JSON.parse(iframeContents);
                    if (iframeContents.status) {
                        $(#prevImg).attr(src, iframeContents.data);
                        $(#formAvatar).val(iframeContents.data);
                    }
                }

            })
        }

    </script>
</body>
</html>

  index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        {% for item in user_list %}
            <li><img style="height: 50px;width: 50px" src="{{ item.avatar }}"> {{ item.user }}</li>
        {% endfor %}
    </ul>
</body>
</html>

 

文件上传及图片预览

标签:class   method   pwd   his   覆盖   formdata   with   line   position   

原文地址:https://www.cnblogs.com/stfei/p/9332470.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!