1. 程式人生 > >Django框架學習筆記(28.檔案上傳詳解)

Django框架學習筆記(28.檔案上傳詳解)

1.所有美觀的上傳按鈕原理:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
.upload {
            display: inline-block;
padding: 10px;
background-color: aqua;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index
: 90; } .file { width: 100px; height: 50px; opacity: 0; position: absolute; top: 0; bottom: 0; left: 0; right: 0; z-index: 100; } </style> </head> <body> <div style="position:relative; width: 100px; height: 50px"> <input class="file" type="file" id="666" name=
"2333"/> <a class="upload">上傳</a> </div> </body> </html>

jQuery的檔案上傳:

<body>
<div style="position:relative; width: 100px; height: 50px">
    <input class="file" type="file" id="f666" name="2333"/>
    <a class="upload">上傳</a>
</div>
<input 
type="button" value="提交jQuery" onclick="jqSubmit();"/> <script src="/static/jquery-1.12.4.js"></script> <script> function jqSubmit() { // $('#fafafa')[0] var file_obj = document.getElementById('f666').files[0]; var fd = new FormData(); fd.append('username', 'root'); fd.append('f666', file_obj); $.ajax({ url: '/upload_file/', type: 'POST', data: fd, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success: function () {} }) } </script> </body>

views.py:

def upload(request):
    return render(request, 'upload.html')
from django.views.decorators.csrf import csrf_exempt, csrf_protect
@csrf_exempt
def upload_file(request):
    username = request.POST.get('username')
    f666 = request.FILES.get('f666')
    with open(f666.name, 'wb') as f:
        for item in f666.chunks():
            f.write(item)

    return HttpResponse('OK')

XHR方式上傳檔案:

<script>
function xhrSubmit(){
            var file_obj = document.getElementById('f666').files[0];
var fd = new FormData();
fd.append('username','root');
fd.append('f666',file_obj);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload_file/',true);
xhr.send(fd);
}

</script>

IFRAME方式上傳:

<body>
<form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
    <iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
    <input type="file" name="f666" onchange="changeUpalod();"/>
    <input type="submit" onclick="iframeSubmit();" value="Form提交"/>
</form>
<script>
</script>
</body>

上傳檔案預覽:

views.py:

from django.views.decorators.csrf import csrf_exempt, csrf_protect
import json
import os
@csrf_exempt
def upload_file(request):
    f666 = request.FILES.get('f666')
    img_path = os.path.join('static/imgs/', f666.name)
    with open(img_path, 'wb') as f:
        for item in f666.chunks():
            f.write(item)
    ret = {'data': img_path}
    return HttpResponse(json.dumps(ret))

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title></head>
<body>
<form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
    <iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
    <input type="file" name="f666" onchange="changeUpalod();"/>
    <input type="submit" onclick="iframeSubmit();" value="提交"/>
</form>
<div id="preview"></div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
function iframeSubmit() {
        $('#ifm1').load(function () {
            var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
$('#preview').empty();
var imgTag = document.createElement('img');
imgTag.src = "/" + obj.data;
$('#preview').append(imgTag);
})
    }
</script>
</body>
</html>

上面的預覽要上傳後才可以,下面這個只要選擇圖片後就可以預覽:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
    <iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
    <input type="file" name="f666" onchange="changeUpload();"/>
    <input type="submit" onclick="iframeSubmit();" value="提交"/>
</form>
<div id="preview"></div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
function changeUpload() {
        $('#ifm1').load(function () {
            var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
$('#preview').empty();
var imgTag = document.createElement('img');
imgTag.src = "/" + obj.data;
$('#preview').append(imgTag);
});
$('#form1').submit();
}


    function iframeSubmit() {
        $('#ifm1').load(function () {
            var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
$('#preview').empty();
var imgTag = document.createElement('img');
imgTag.src = "/" + obj.data;
$('#preview').append(imgTag);
})
    }
</script>
</body>
</html>