天天看點

檔案上傳 前後端完整流程 - Vue+Django開發

一. 建立Django項目

檢視是否安裝Django: `django-admin --version’
# 建立項目
django-admin startproject mysite
# 建立應用
py manage.py startapp fileUpload
# 運作項目
py manage.py runserver      

二. 建立Vue項目

使用vue-cli腳手架建立新項目

安裝vue-cli前, 需要先安裝好 nodejs
# 全局安裝vue-cli工具
npm install vue-cli -g
# 建立新項目
vue init webpack vue-project


# 項目正常啟動, 安裝vue輔助工具
npm install vue-router --save
npm install vuex --save
npm install vue-resource --save
npm install axios --save

# 運作項目
npm run dev      

Tip: ​​vue——解決“You may use special comments to disable some warnings. Use // eslint-disable-next-line to ignore the next line. Use /* eslint-disable */ to ignore all warnings in a file. ”​

在build/webpack.base.conf.js檔案中,注釋或者删除掉:module->rules中有關eslint的規則

module: {

rules: [

//...(config.dev.useEslint ? [createLintingRule()] : []), // 注釋或者删除

{

test: /\.vue$/,

loader: 'vue-loader',

options: vueLoaderConfig

},

...

}

]

}

然後 npm run dev 就能正常運作了

三. Vue代碼實作:

3.1 添加子元件

在 components 檔案下建立一個自己的 元件檔案(FileUpload.vue)

<template>
    <div class="upload">
        <form>
            {{ name }}
            <br><br>
            <input type="file" value="" id="file"  accept=".doc,.docx,.txt" @change="getFile($event)">
            <button @click="submitForm($event)">送出</button>
            <br>
            {{ checkStatus }}
        </form>
    </div>
</template>

<script>
export default {
    name:"upload",
    data() {
        return {
            name: "上傳檔案",
            checkStatus: ""
        }
    },
    methods: {
        getFile(event) {
            this.file = event.target.files[0],
            console.log(this.file)
        },
        submitForm(event) {
            
            // event.preventDefault();
            let formData = new FormData();
            formData.append('file', this.file);
            let config = {
                headers: {
                    'Content-Type':'multipart/form-data'
                }
            };

            // 建立一個空的axios 對象
            const instance=this.$axios.create({
                withCredentials: true,      // 如果發送請求的時候需要帶上token 驗證之類的也可以寫在這個對象裡
                headers: {
                    'Content-Type':'multipart/form-data'
                }
            }) 

            instance.post('http://127.0.0.1:8000/fileUpload/upload/',formData).then(res=>{
                if(res.data.code === 200) {
                    alert(res.data.msg);
                    this.checkStatus = res.data;
                }else if(res.data.code === 2) {
                    alert(res.data.msg)
                }else{
                    alert(res.data.msg);
                }
            })

        }
    },
}
</script>

<style scoped>

</style>      

子元件建立好後 就要注冊它,隻有注冊了才能使用

3.2 全局注冊

main.js:

檔案上傳 前後端完整流程 - Vue+Django開發

App.vue:

檔案上傳 前後端完整流程 - Vue+Django開發

四. Django代碼實作

4.1 mysite->setting.py通過設定解決跨域問題

cmd運作: ​

​python -m pip install django-cors-headers​

​​

解決跨域問題

在setting.py檔案中增加下面内容

# 跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = [
    'http://127.0.0.1:8080'
]

CORS_ALLOW_METHODS  =  [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)      

并添加下面兩行代碼

檔案上傳 前後端完整流程 - Vue+Django開發

如果出現403錯誤,請看:​​Forbidden (403) CSRF verification failed. Request aborted. - Django​

4.2 添加接口資訊

mysite檔案夾下的​

​urls.py​

​添加紅框内容:

from django.urls import path
from . import views


urlpatterns = [
    path('upload/', views.index, name='index'),
    path('check/', views.check, name='check'),
]      

4.3 fileUpload->views.py代碼

import json
import os
import re
import time
import uuid

from django.http import HttpResponse
from django.middleware.csrf import get_token
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.conf import settings


@require_http_methods(["GET", "POST"])
@csrf_exempt
def index(request):
    response = {}
    try:
        if request.method == 'GET':
            get_token(request)
        if request.method == 'POST':
            req = request.FILES.get('file')

            #  上傳檔案類型過濾
            file_type = re.match(r'.*\.(txt|doc|docx)', req.name)
            if not file_type:
                response['code'] = 2
                response['msg'] = '檔案類型不比對, 請重新上傳'
                return HttpResponse(json.dumps(response))

            # 将上傳的檔案逐行讀取儲存到list中
            file_info = {'date': '', 'name': '', 'uuid': '', 'path': ''}
            content = []
            for line in req.read().splitlines():
                content.append(line)

            # 打開特定的檔案進行二進制的寫操作
            destination = open(
                os.path.join("d://file", req.name), 'wb+')
            for chunk in req.chunks():  # 分塊寫入檔案
                destination.write(chunk)
            destination.close()

            # 生成目前檔案生成UUID
            file_info['uuid'] = uuid.uuid1()
            # 上傳檔案的時間
            time_stamp = time.time()
            now = int(round(time_stamp * 1000))
            file_info['date'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now / 1000))
            # 檔案名稱
            file_info['name'] = req.name


            # 傳回狀态資訊
            response['check'] = check(content)
            response['msg'] = "Success"
            response['code'] = 200

    except Exception as e:
        response['msg'] = '伺服器内部錯誤'
        response['code'] = 1
    return HttpResponse(json.dumps(response), content_type="application/json")


@csrf_exempt
def check(list):
    print(list)
    return '校驗中'