django接口
#定义上传文件夹的路径
UPLOAD_ROOT = os.path.join(BASE_DIR,'static/upload')
urlpatterns = [
#定义超链接路由
re_path('^static/upload/(?P<path>.*)$',serve,{'document_root':'/static/upload/'}),
path('',myindex),
path('upload/',UploadFile.as_view())
]
#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os
# 文件上传通用类
class UploadFile(APIView):
def post(self,request):
# 接收参数
myfile = request.FILES.get('file')
# 建立文件流对象
f = open(os.path.join(UPLOAD_ROOT,'',myfile.name.replace('"','')),'wb')
for chunk in myfile.chunks():
f.write(chunk)
f.close()
return Response({'filename':myfile.name.replace('"','')})
vue
<template>
<div>
<div>
<img src="src" alt="">
<Avatar :src="src" :width="150" fit="fill"></Avatar>
</div>
<div>
<table>
<tr>
<td>
用户头像:
</td>
<td>
<input type="file" @change="upload">
</td>
</tr>
</table>
</div>
</div>
</template>
<script>
//导入组件
import myheader from './myheader.vue';
export default {
data () {
return {
msg: "这是一个变量",
src: '',
//面包屑导航变量
datas:[{title:'首页',route:{name:'index'}},{title:'用户中心-->首页'}],
}
},
//注册组件标签
components:{
'myheader': myheader,
},
mounted:function(){
},
methods:{
//定义提交事件
upload:function(e){
// 获取文件
let file = e.target.files[0];
// 声明表单参数
let param = new FormData();
param.append('file',file,file.name);
// 声明请求头
let config = {headers:{'Content-Type':'multipart/form-data'}}
// 请求后台接口
this.axios.post('http://localhost:8000/upload/',param,config).then((result) =>{
console.log(result);
this.src = "http://localhost:8000/static/upload/"+result.data.filename;
});
},
}
}
</script>