models
from django.db import models
from django.utils import timezone
class File(models.Model):
# 文件名称
name = models.CharField(max_length=50)
# 文件保存路径
# path = models.CharField(max_length=100)
# 上传时间
upload_time = models.DateTimeField(default=timezone.now)
# upload上传功能实现,to上传后保存的路径
file = models.FileField(upload_to='fileAPI/file/')
serializer
from fileAPI.models import File
from rest_framework import serializers
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = File
# 序列化所有的字段
fields = '__all__'
app urls
from django.urls import path
from .views import *
urlpatterns = [
# 下载
path('download/<id>', download_file),
]
项目urls
path('testapi/File/', include('fileAPI.urls')),
views
def create(self, request):
"""
上传文件
:param request:POST
:param:
:return:
"""
# 选择的文件
files = request.FILES.getlist('file')
# 遍历写入到数据库中
for file in files:
# 写入到数据库中
file_model = File(name=file.name, file=request.FILES['file'])
file_model.save()
print(files)
return HttpResponse('this is create')
<template>
<div class="app-container">
<el-upload
class="upload-demo"
action=""
:http-request="upload"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
upload(param) {
const formData = new FormData()
formData.append('file', param.file)
const url = axios.defaults.baseURL + 'testapi/File/'
axios.post(url, formData).then(data => {
console.log('上传图片成功')
}).catch(response => {
console.log(response)
})
}
}
}
</script>