文件上传 前后端完整流程 - 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 '校验中'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章