首页 > 其他分享 >文件上传 前后端完整流程 - Vue+Django开发

文件上传 前后端完整流程 - Vue+Django开发

时间:2022-11-04 18:31:07浏览次数:56  
标签:vue name data py Django Vue file 上传 response


一. 创建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开发_python

App.vue:

文件上传 前后端完整流程 - Vue+Django开发_Django_02

四. 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开发_django_03


如果出现403错误,请看:​​Forbidden (403) CSRF verification failed. Request aborted. - Django​

4.2 添加接口信息

mysite文件夹下的​​urls.py​​添加红框内容:

文件上传 前后端完整流程 - Vue+Django开发_django_04

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 '校验中'


标签:vue,name,data,py,Django,Vue,file,上传,response
From: https://blog.51cto.com/u_14233037/5824482

相关文章

  • PHP WEB怎么实现大文件上传
    ​PHP用超级全局变量数组$_FILES来记录文件上传相关信息的。1.file_uploads=on/off 是否允许通过http方式上传文件2.max_execution_time=30 允许脚本最大执行时间......
  • 记录--vue中动态引入图片为什么要是require, 你不知道的那些事
    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助相信用过vue的小伙伴,肯定被面试官问过这样一个问题:在vue中动态的引入图片为什么要使用require有些小伙伴......
  • Vue3 实用工具分享
    以下脑图内容分成了8大类,分别是WebUI库、移动UI库、相关工具、可视化、插件、相关生态、动画、音频。在脑图中每类工具用不同的颜色区分,方便你查找。不仅仅是给你分好类......
  • C# WEB怎么实现大文件上传
    ​HTML部分 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="up6.index" %><!DOCTYPE html PUBLIC "-//W3C//DTDXHTM......
  • Vue表单验证插件Vue Validator使用方法详解
    https://www.jb51.net/article/110609.htmVue-validator是Vue的表单验证插件,供大家参考,具体内容如下Vue版本:1.0.24Vue-validator版本:2.1.3基本使用12345......
  • Vue 二 --数据绑定
    Vue中有2种数据绑定的方式:1.单向绑定(v-bind):数据只能从data流向页面。2.双向绑定(v-model):数据不仅能从data流向页面,还可以从页面流向data。备注:......
  • Vue 三 el与data的两种写法
    data与el的2种写法1.el有2种写法(1).newVue时候配置el属性。(2).先创建Vue实例,随后再通过vm.$mount('#root')指定el的值。......
  • 大文件上传如何做断点续传
    ​ 1,项目调研因为需要研究下断点上传的问题。找了很久终于找到一个比较好的项目。 在GoogleCode上面,代码弄下来超级不方便,还是配置hosts才好,把代码重新上传到了githu......
  • vuejs 前端 使用axios发送get、post请求 参数在query和body里面的各种情况
    使用axios发送get请求,参数写在query里letres=awaitthis.$axios.get('/user/b/getOrgList',{params:{pageNo:1,pageSize:......
  • hadoop之上传文件报错.md
    问题​ 采用CDH搭建的hadoop集群环境,命令行上传文件正常,Java代码上传报如下错误couldonlybereplicatedto0nodesinsteadofminReplication(=1).Thereare3da......