django+python大文件上傳-創(chuàng)新互聯(lián)

大文件上傳服務(wù)
一、前端
[webuploader](http://fex.baidu.com/webuploader/ ''webuploader'')
二、后端
django 2.0.0
這里只貼出核心的代碼:
前端的:

成都創(chuàng)新互聯(lián)公司自2013年起,先為都昌等服務(wù)建站,都昌等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為都昌企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--引入CSS-->
<link rel="stylesheet" type="text/css" >
<link rel="stylesheet" type="text/css" >

<!--引入JS-->
<script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/webuploader/0.1.1/webuploader.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/twitter-bootstrap/4.1.3/js/bootstrap.js"></script>
</head>
<body>
<div id="uploader" class="wu-example">
    <!--用來(lái)存放文件信息-->
    <div id="thelist" class="uploader-list"></div>
    <div class="btns">
        <div id="picker">選擇文件</div>
        <button id="ctlBtn" class="btn btn-default">開始上傳</button>
    </div>
    <div class="progress">         <!-- 進(jìn)度條 -->
            <div class="progress-bar progress-bar-striped active" role="progressbar" ></div>
        </div>
</div>
 <script type="text/javascript">
    $(document).ready(function() {
        var task_id = WebUploader.Base.guid();        //產(chǎn)生task_id
        var uploader = WebUploader.create({           //創(chuàng)建上傳控件
            swf: 'https://cdn.staticfile.org/webuploader/0.1.1/Uploader.swf', //swf位置,這個(gè)可能與flash有關(guān)
            server: '/resource/files/upload/',                 //接收每一個(gè)分片的服務(wù)器地址
            pick: '#picker',                          //填上傳按鈕的id選擇器值
            auto: true,                               //選擇文件后,是否自動(dòng)上傳
            chunked: true,                            //是否分片
            chunkSize: 10 * 1024 * 1024,              //每個(gè)分片的大小,這里為10M
            chunkRetry: 3,                            //某分片若上傳失敗,重試次數(shù)
            threads: 1,                               //線程數(shù)量,考慮到服務(wù)器,這里就選了1
            duplicate: true,                          //分片是否自動(dòng)去重
            formData: {                               //每次上傳分片,一起攜帶的數(shù)據(jù)
                task_id: task_id,
            },
        });

        uploader.on('startUpload', function() {       //開始上傳時(shí),調(diào)用該方法
            $('.progress-bar').css('width', '0%');
            $('.progress-bar').text('0%');
        });

        uploader.on('uploadProgress', function(file, percentage) { //一個(gè)分片上傳成功后,調(diào)用該方法
            $('.progress-bar').css('width', percentage * 100 - 1 + '%');
            $('.progress-bar').text(Math.floor(percentage * 100 - 1) + '%');
        });

        uploader.on('uploadSuccess', function(file) { //整個(gè)文件的所有分片都上傳成功,調(diào)用該方法
            //上傳的信息(文件唯一標(biāo)識(shí)符,文件名)
            var data = {'task_id': task_id, 'filename': file.source['name'] };
            $.get('/resource/upload/complete/', data);          //ajax攜帶data向該url發(fā)請(qǐng)求
            $('.progress-bar').css('width', '100%');
            $('.progress-bar').text('上傳完成');
        });

        uploader.on('uploadError', function(file) {   //上傳過(guò)程中發(fā)生異常,調(diào)用該方法
            $('.progress-bar').css('width', '100%');
            $('.progress-bar').text('上傳失敗');
        });

        uploader.on('uploadComplete', function(file) {//上傳結(jié)束,無(wú)論文件最終是否上傳成功,該方法都會(huì)被調(diào)用
            $('.progress-bar').removeClass('active progress-bar-striped');
        });

    });
    </script>

</body>
</html>

后端的:
路由

path('files/upload/', views.fileupload,name='圖片分片上傳'),
    path('upload/complete/', views.fileMerge,name='上傳成功合并'),

視圖:

@csrf_exempt
def fileupload(request):
    if request.method == 'POST':
        upload_file = request.FILES.get('file')
        task = request.POST.get('task_id')  # 獲取文件唯一標(biāo)識(shí)符
        chunk = request.POST.get('chunk', 0)  # 獲取該分片在所有分片中的序號(hào)
        filename = '%s%s' % (task, chunk)  # 構(gòu)成該分片唯一標(biāo)識(shí)符
        print("filename=",filename)
        default_storage.save('./upload/%s' % filename,ContentFile(upload_file.read()))  # 保存分片到本地
    return render_to_response('upload.html',locals())

@csrf_exempt
def fileMerge(request):
    print(request.GET)
    task = request.GET.get('task_id')
    ext = request.GET.get('filename', '')
    upload_type = request.GET.get('type')
    if len(ext) == 0 and upload_type:
        ext = upload_type.split('/')[1]
    ext = '' if len(ext) == 0 else '.%s' % ext  # 構(gòu)建文件后綴名
    chunk = 0
    with open('./upload/%s%s' % (task, ext), 'wb') as target_file:  # 創(chuàng)建新文件
        while True:
            try:
                filename = './upload/%s%d' % (task, chunk)
                source_file = open(filename, 'rb')  # 按序打開每個(gè)分片
                target_file.write(source_file.read())  # 讀取分片內(nèi)容寫入新文件
                source_file.close()
            except IOError:
                break
            chunk += 1
            os.remove(filename)  # 刪除該分片,節(jié)約空間
    return render_to_response('upload.html',locals())

效果圖:
django+python大文件上傳

創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國(guó)云服務(wù)器,動(dòng)態(tài)BGP最優(yōu)骨干路由自動(dòng)選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動(dòng)現(xiàn)已開啟,新人活動(dòng)云服務(wù)器買多久送多久。

網(wǎng)站名稱:django+python大文件上傳-創(chuàng)新互聯(lián)
文章出自:http://bm7419.com/article16/cdgsgg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、ChatGPT網(wǎng)站導(dǎo)航、電子商務(wù)、網(wǎng)站策劃、網(wǎng)站設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)