美文网首页
文件上传

文件上传

作者: LittleJessy | 来源:发表于2019-01-09 14:54 被阅读0次

    第一步:html写UI

        <div style="padding-top:20px;">
            <form enctype="multipart/form-data" class="navbar-form" action="/qm/xradar/upload_data/" method="post">
                <div class="form-group">
                    <input type="file" class="form-control" name="myfile"/>
                </div>
                <div class="form-group">
                    <input type="submit" class="layui-btn" value="上传"/>
                </div>
                {% csrf_token %}
            </form>
        </div>
    

    加入提示信息

        <script>
            $(function () {
                Uploadfile();
            });
    
            //判断上传文件是否为空
            function Uploadfile() {
                var upload_msg;
                upload_msg = "{{ upload_msg }}";
                if (upload_msg == 2) {
                    alert("上传成功!");
                }
                if (upload_msg == 1) {
                    alert("请选择上传文件!");
                }
                if (upload_msg == 3) {
                    alert("文件上传失败!");
                }
            }
        </script>
    

    第二步:qmviews.py文件编写视图函数

    @login_Check
    def upload_data(request):
        if request.method == "POST":  # 请求方法为POST时,进行处理
            myFile = request.FILES.get("myfile", None)  # 获取上传的文件,如果没有文件,则默认为None
            if not myFile:
                upload_msg = 1
            else:
                try:
                    cur_path = os.path.abspath('...')
                    CUR_PATH = cur_path + '\\upload\\qm\\'
    
                    destination = open(os.path.join(CUR_PATH, myFile.name), 'wb+')  # 打开特定的文件进行二进制的写操作
                    for chunk in myFile.chunks():  # 分块写入文件
                        destination.write(chunk)
                    destination.close()
                    upload_msg = 2
                    writeLog_info('[文件%s],上传成功!' % (myFile.name))
                except Exception as e:
                    upload_msg = 3
                    writeLog_error('[文件%s],上传失败:%s' % (myFile.name,e))
        return render(request, "../templates/qm/xradar.html", {"upload_msg": upload_msg})
    

    第三步:urls.文件添加路由

        url('^xradar/upload_data/$', qmviews.upload_data),
    
    image.png
    image.png
    image.png
    image.png
    image.png

    相关文章

      网友评论

          本文标题:文件上传

          本文链接:https://www.haomeiwen.com/subject/abvqfqtx.html