python+Django+vue+iview上传问文件的坑
权限问题
在后台,使用View和APIView有不同的权限访问
from rest_framework.views import APIView
from django.views import View
使用View时,前端接口不用请求头和用请求头都不会报权限问题
使用APIView时,前端不能使用请求头也就是
headers: {
‘Content-Type’: ‘multipart/form-data’
}
后台代码
1、url.py 请求连接(前后端数据交互接口)
app_name = "maintaintools"
urlpatterns = [
path('uploadfile/file', tests.FileUploadView.as_view())
]
2、test.py 处理前端的上传文件和数据
"""文件上传"""
class FileUploadView(View):
'''
上传文件接口
'''
def post(self,request):
"""
返回上传的文件地址
"""
print(self)
print(request)
print(request.POST)
try:
files = request.FILES.getlist('file', None) # 文件
print('1111111111111')
print(files)
data = request.POST.get('data', None) # 携带参数
print('22222222222')
print(data)
# from db_monitor import settings
# if filemkdir not in settings.DATA_FILENAAME or not files:
# return HttpResponse({"code":400, "msg":u"上传参数无效"})
# if filemkdir == 'attachment':
# self.IMG_result = self.attachment_uploading(files)
# else:
# self.IMG_result = self.file_upload(files=files,mk=filemkdir)
# return HttpResponse(self.IMG_result)
return HttpResponse('999999999999999999999999999')
except Exception as e:
print(e)
return HttpResponse({"code": 400, "msg": u"上传失败"})
前端代码
前端代码使用vue+iview,连接跳转使用路由封装的接口进行前后端数据交互
- 前端请求接口
请求头
headers: {‘Content-Type’: ‘multipart/form-data’}
在这里是否使用取决于后台使用View还是APIView,如果后台使用APIView,这里无需加请求头,不然会报401权限问题
export const upload_fileall = (date) => {
return axios.request({
method: 'post',
url: `/maintaintools/uploadfile/file`,
data:date,
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
- test.vue页面代码
<template>
<div class="layout">
<div class="left">
<div style="width: 50%;height: 50%;">
<!-- multiple filterable allow-create 获取需要上传文件的服务器主机-->
<div>
<span style="margin-left: 20px">已选择的:</span>
<span style="margin-left: 10px" v-for="val in formsshtags" :key="val.tags">{{val.tags}}</span>
</div>
<Form :label-width="80">
<FormItem label="数据列表" prop="get_linux_tags">
<Select
multiple
:max-tag-count="1"
v-model="formsshtags" filterable allow-create>
<Option v-for="item in linuxdata" :value="item" :key="item.tags" :label="item.tags">{{item.tags}}</Option>
</Select>
</FormItem>
</Form>
<Upload
multiple
ref="upload"
type="drag"
:on-preview="handlePreview"
:data="uploadData"
:on-error = "error"
:on-success="successResave"
:on-remove="handleRemove"
:file-list="fileList"
:before-upload="beforeUpload"
action=""
class="uploadfile">
<div style="width: 50%;height:80%; margin: auto ;">
<Icon type="ios-cloud-upload" style="color: #3399ff;" size="130" ></Icon>
<p>点击或拖拽文件上传</p>
</div>
</Upload>
</div>
</div>
</div>
</template>
- js代码,实现方法
<script>
import { getLinuxList, upload_fileall } from '@/api/maintaintools'
import {formatDate} from "../../libs/tools";
export default {
data () {
return {
linuxdata: [], // 数据集合
formsshtags: [],// 获取选中的服务器数据
get_linux_tags: [],
file:null,
}
},
// vue生命周期,打开页面就加载的数据放在这里
created () {
this.get_linux_list()
},
methods: {
// 获取主机信息
get_linux_list (parameter) {
getLinuxList(parameter).then(res => {
this.linuxdata = res.data.results
}).catch(err => {
this.$Message.error(`获取Linux主机资源信息错误 ${err}`)
})
},
//上传前操作,用于判断文件类型,大小,限制等操作
beforeUpload(file){
let from_data=new FormData();
this.file=file;
from_data.append('file',this.file)
from_data.append('data',this.formsshtags)
upload_fileall(from_data).then(res=>{//将对象和文件一并通过接口传给后台
console.log(res.url)
}).catch(err =>{
this.$Message.error(`上传错误 ${err}`)
})
return false;
},
//文件上传的状态
loadingStatus(){
this.$Message.error('上传失败')
},
//返回成功
uploadSucess(response, file, fileList){
// this.$Message.info(response.msg);
// this.$Message.info(file);
// this.$Message.info(fileList);
console.log(response)
console.log(file)
console.log(fileList)
console.log(this.response.data)
},
//返回失败
uploadError(){
},
}
}
</script>
- 上传携带参数如图
5、下面就是对文件进行各种操作的了,上传配置文件保存路径和做文件上传分类等