python之路--web--2--Django-13-Django上傳文件的三種方式

方式一:html

經過form表單提交到後臺jquery

前段:ajax

複製代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/upload/" method="post" enctype="multipart/form-data">
        <input type="file" name="fafafa">
        <input type="submit">
    </form>
</body>
</html>
複製代碼

Django 後端:後端

複製代碼
def upload(request):
    if request.method == 'POST':# 獲取對象
        obj = request.FILES.get('fafafa')
        import os
    # 上傳文件的文件名
    print(obj.name) f = open(os.path.join(BASE_DIR, 'static', 'pic', obj.name), 'wb') for chunk in obj.chunks(): f.write(chunk) f.close() return HttpResponse('OK') return render(request, 'upload/upload.html')
複製代碼

 方式二:app

經過ajax提交ide

前段post

<div>
        <input type="file" name="file" id="file_upload">
        <input type="button" value="上傳" onclick="FileUpload()">
</div>

JS:url

複製代碼
<script src="/static/js/jquery-3.2.1.min.js"></script>
<script>
    function FileUpload() {
            var form_data = new FormData();
            var file_info =$( '#file_upload')[0].files[0];
            form_data.append('file',file_info);
            //if(file_info==undefined)暫且不準要判斷是否有附件
                //alert('你沒有選擇任何文件');
                //return false
            $.ajax({
                url:'/upload_ajax/',
                type:'POST',
                data: form_data,
                processData: false,  // tell jquery not to process the data
                contentType: false, // tell jquery not to set contentType
                success: function(callback) {

                    console.log('ok')
                }
            });

            }</script>
複製代碼

Django 後端:spa

複製代碼
def upload_ajax(request):
    if request.method == 'POST':
        file_obj = request.FILES.get('file')
        import os
        f = open(os.path.join(BASE_DIR, 'static', 'pic', file_obj.name), 'wb')
        print(file_obj,type(file_obj))
        for chunk in file_obj.chunks():
            f.write(chunk)
        f.close()
        print('11111')
        return HttpResponse('OK')
複製代碼

注意:code

前臺發送ajax請求時:

processData: false, // tell jquery not to process the data
contentType: false, // tell jquery not to set contentType
必須設置

方式三:
經過iframe標籤提交
前段:
複製代碼
   <div>
        <form id="my_form" name="form" action="/upload_iframe/" method="POST" enctype="multipart/form-data">
            <input type="text" name="user">
            <input type="password" name="password">
            <input type="file" name="file">
            <input type="button" value="upload"  onclick="UploadFile()">
        </form>
        <iframe id='my_iframe' name='my_iframe' src="" class="hide"></iframe>
    </div>
複製代碼

JS:

複製代碼
    function UploadFile() {
        document.getElementById('my_iframe').onload = Testt;
        document.getElementById('my_form').target = 'my_iframe';
        document.getElementById('my_form').submit();
    }
    function Testt(ths){
            var t = $("#my_iframe").contents().find("body").text();
            console.log(t);
        }
複製代碼

Django 後端:

複製代碼
def upload_iframe(request):
    if request.method == 'POST':
        print(request.POST.get('user', None))
        print(request.POST.get('password', None))
        file_obj = request.FILES.get('file')
        import os
        f = open(os.path.join(BASE_DIR, 'static', 'pic', file_obj.name), 'wb')
        print(file_obj,type(file_obj))
        for chunk in file_obj.chunks():
            f.write(chunk)
        f.close()
        print('11111')
        return HttpResponse('OK')
複製代碼

以上是文件上傳的三種方式,在Tornado種也可使用。

擴展:

在前段提交的時候 能夠存在 checkbox 標籤, 在Django中對於這種標籤在後臺獲取值時用:

  request.POST.getlist('favor', None) checkbox

其它

request.POST.get('favor', None) checkbox
相關文章
相關標籤/搜索