文件上傳 前後端完整流程 - 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:
在這裏插入圖片描述

App.vue:
image-20200612135152664

四. 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',
)

並添加下面兩行代碼
在這裏插入圖片描述
如果出現403錯誤,請看:Forbidden (403) CSRF verification failed. Request aborted. - Django

4.2 添加接口信息

mysite文件夾下的urls.py添加紅框內容:
在這裏插入圖片描述

fileUpload文件夾下新建 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 '校驗中'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章