前言:最近做前后端连接时遇到的问题,项目由本地文件前端上传至后端
项目需要:element-plus库,vue3,django
一.Vue的上传部分
1.HTML 部分
<template>
<div>
<div> // 通过一个button 组件和一个 input 组件完成前端上传的HTML部分
<el-button @click="uploadFile" id="upload"
type="primary" round class="right"
size="default">Upload</el-button>
</div>
<input ref="file" type="file" @change="onFileChange" style="display: none;"/>
// 去除input 外观
</div>
</template>
2.js部分
<script>
import axios from "axios"; // axios 需要自行下载 运行 npm install axios
export default {
methods: {
async onFileChange(e) {
this.file = e.target.files[0]; // 可以不在data 中声明
const formData = new FormData();
formData.append("file", this.file);
console.log(this.file);
try {
// 向upload页面上传
const response = await axios.post("http://127.0.0.1:8000/upload/", formData);
console.log(response);
this.$emit("change", this.file); //并将当地的文件上传至父组件(可删去)
} catch (error) {
console.error("Error uploading file:", error);
}
},
uploadFile() {
this.$refs.file.click();
},
}
};
</script>
呈现效果 :
过渡:学习django初始化
二.django的接收(本文暂写txt文本类型的接收)
1.下载 corsheaders 指令:
pip install django-cors-headers
2.生成app 并注册corsheaders 与app
1.命令行指令
# 最后跟的是app的名称
python manage.py startapp api
2.注册app 及相应的corsheaders
# setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api', # 注册上你的app 名字
'corsheaders', # 注册上corsheaders
]
MIDDLEWARE = [
#一定要注释掉'django.middleware.csrf.CsrfViewMiddleware'
#并加上'corsheaders.middleware.CorsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# 并注明可以访问的域名(博主选择的是所有域名都可以访问)
CORS_ORIGIN_ALLOW_ALL = True
3.models 及views 相关配置
#models.py
from django.db import models
import os
# Create your models here.
class FileOperation:
@staticmethod
def handle_upload_file_txt(file,filename):
path = r'./txt/' # txt保存途径
print(f"filename={filename}")
if not os.path.exists(path):
os.makedirs(path)
with open(path + filename, 'w',encoding='utf-8') as destination:
content = file.read()
content = str(content, encoding = 'utf-8')
# print(chunk)
destination.write(content)
#views.py
from django.http import HttpResponse
from django.shortcuts import render
import json
from api.models import FileOperation
# Create your views here.
def getnewoption(request):
if request.method == "POST":
r_list = json.loads(request.body) # 前端向后端发送的参数
# 对r_list进行操作,结果存入arr。以dict数据类型{'id': '', 'file': ''}格式存储,方便后续取用;
arr = [] # 后端返回前端的参数
return HttpResponse(json.dumps(arr, ensure_ascii=False), content_type='application/json', charset='utf-8')
# @csrf_exempt # 没加这个会报错Forbidden (CSRF cookie not set.)
def upload(request):
if request.method == "POST":
FileOperation.handle_upload_file_txt(request.FILES.get('file'), str(request.FILES['file']))
return HttpResponse('yes')
4.urls配置
# urls.py (主项目中的urls.py)
from django.contrib import admin
from django.urls import include, path
from api import views
urlpatterns = [
path('admin/', admin.site.urls),
path('upload/', views.upload),
]
三.实现效果
注释:需要前后端两个项目都运行才可
前端呈现