前端上传文件代码:
<template>
<div>
<div>
<el-upload class="upload-demo" ref="upload" action="http://127.0.0.1:8000/data/" :on-preview="handlePreview"
:on-remove="handleRemove" :on-success="handleSuccess" :on-error='handleFail' :file-list="fileList"
:multiple="false" :limit="1" :auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选择文件</el-button>
</el-upload>
</div>
<div>
<el-button slot="trigger" size="small" type="success" @click="submitUnpload()">上传文件</el-button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
fileList: [],
data: [],
}
},
methods: {
handleFail() {
this.$message({
type: 'error',
message: '上传失败',
duration: 1000
})
},
// 成功上传到服务器后返回的内容
handleSunccess(e) {
this.data = e
},
// 上传文件到服务器
submitUnpload() {
this.$refs.upload.submit()
this.$message({
type: 'success',
message: '上传成功',
duration: 1000
})
},
// 删除文件
handleRemove(file) {
this.$message({
type: "success",
message: "删除成功",
duration: 1000
})
},
}
}
</script>
<style>
</style>
Django获取前端上传的文件:
class Data(APIView):
def post(self, request):
file_obj = request.FILES.get("file")
......
通过csv模块读取csv文件,不需要打开文件,通过read()方法读取后传给csv.reader()
class Data(APIView):
def post(self, request):
file_obj = request.FILES.get("file")
file_data = file_obj.read().decode("utf-8-sig")
rows = csv.reader(io.StringIO(file_data), delimiter=',')
for row in rows:
row #读取的数据
pandas读取:
class StatisticDmanday(APIView):
def post(self, request):
file_obj = request.FILES.get("file")
df = pd.read_csv(file_obj)
openpyxl读取excel文件:
class StatisticDmanday(APIView):
def post(self, request):
wb = openpyxl.load_workbook(file_obj)
sheetnames = wb.get_sheet_names()
ws = wb.get_sheet_by_name(sheetnames[0])