web前端上传文件按钮自定义样式

思路:

按钮进行隐藏,样式自己该怎么写怎么写,之后通过js监测input改变上传文件。

前端写法:

// jquery + bootstrap写法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件获取URL</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    <style>

        .uploader{
            position: relative;
        }

        .uploader input{
            position: absolute;
            top: 4px;
            opacity: 0;
            width: 100%;
        }

    </style>
</head>
<body>

<div class="container-fluid">

    <div class="row" style="margin: 0 0;margin-top: 20px;">
        <div class="col-md-1">
            <div class="uploader">
                <button class="btn btn-primary">上传图片</button>
                <form id="file_form">
                    <input type="file" id="file" name="file">
                </form>
            </div>
        </div>
    </div>

    <hr>

    <div class="row">

    </div>

</div>

<script src="/static/js/jquery.js"></script>
<script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script>

    function start() {
        // 上传文件
        upload_file();
    }

    function upload_file() {
        $('#file').change(function () {
            var data = new FormData($('#file_form')[0]);
            // 上传文件
            $.ajax({
                url:`/v1/api/answer/kf_type/${kf_type}/upload/`,
                type:'post',
                data:data,
                processData:false,  //表示不处理数据
                contentType:false,  //不设置数据类型
                dataType: 'json',
                success:function (response) {
                    alert(response["message"]);
                    if (last_page_url !== ''){
                        get_info(last_page_url);
                    }else{
                        get_info();
                    }
                    // 清空文件,为下次文件上传做准备
                    $('#file').val('');
                }
            });

        })
    }

    start();

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

django后端视图写法:

def image_upload(req):
    file = req.FILES.get('file')
    value = file.read()
    return HttpResponse("ok")

// value就是文件内容

前端效果图:

 // 样式根据自己进行调节即可,我大概写的

原文地址:https://www.cnblogs.com/zezhou/p/12607143.html