美文网首页
vue antd admin结合django rest fram

vue antd admin结合django rest fram

作者: 万州客 | 来源:发表于2020-12-27 11:15 被阅读0次

这个功能,之前使用jqury实现过。对vue确实不很熟悉,前后搞了近一周的晚上时间。终于实现了一个最基础的手动上传功能。

参考URL:
https://www.antdv.com/components/upload-cn/
一,上传template代码

                        <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
                            <a-button> <a-icon type="upload" /> 选择样本 </a-button>
                        </a-upload>
                        <a-button
                            type="primary"
                            accept=".csv,.xls,.xlsx"
                            :disabled="fileList.length === 0"
                            :loading="uploading"
                            style="margin-top: 16px"
                            @click="handleUpload"
                        >
                            {{ uploading ? '上传导入中' : '导入' }}
                        </a-button>

二,上传涉及的data变量

  data () {
    return {
            fileList: [],
            uploading: false
    }
  }

三,上传涉及的方法

        handleRemove(file) {
            const index = this.fileList.indexOf(file);
            const newFileList = this.fileList.slice();
            newFileList.splice(index, 1);
            //这里配合beforeUpload里的非注释部分,实现单文件上传
            this.fileList = [];
        },
        beforeUpload(file) {
            //this.fileList = [...this.fileList, file];
            this.fileList = [file];
            return false;
        },
        handleUpload() {
            const { fileList } = this;
            const formData = new FormData();
            formData.append('file', this.fileList[0]);
            const fileName = formData.get('file')['name'];
            this.uploading = true;
            // 用纯的axios可以搞定,但使用二次封装过的,暂时有问题。
            const instance = axios.create({
              withCredentials: true  //表示跨域请求时是否需要使用凭证,默认为false
            })
            const url = `http://127.0.0.1:8000/sample/upload_file/${fileName}/`
            console.log(url)
            instance.post(url,formData).then(resp => {
                let retData = resp.data
                if (retData.code == 0) {
                    this.fileList = [];
                    this.uploading = false;
                    this.$message.success('成功导入.');
                } else {
                    this.uploading = false;
                    this.fileList = [];
                    this.$message.error('导入失败.');
                }
                this.fetch(this.pagination)
            })
        },

为减少文件处理难度,这里使用了单个文件上传。
主要就是卡在后台不能接收到前端传的文件,试了N种办法和实现,最后,发现使用纯纯的axios是最省事的。


2020-12-27 11_14_12-悬浮球.png

四,django rest framework后端的url

urlpatterns += [
    path('upload_file/<str:filename>/', api_upload_views.UploadSampleView.as_view(), name='upload_file'),
]

五,DRF的APIVIEW实现

class UploadSampleView(APIView):

    def post(self, request, filename, format=None):
        try:
            # 前端的axios,最好不要用二次封装的,对请求头有统一处理,可能会传不过来。纯的axios可以搞定。
            file_path = request.data['file']
            uu_id = str(int(round(time.time() * 1000)))
            sample_set_upload_id = uu_id + '_sample_set'
            f = SampleSetUpload(sample_set_upload_id=sample_set_upload_id,
                                create_user=request.user,
                                file_name=filename,
                                file_path=file_path)
            f.save()
            csv_reader = csv.reader(open(str(f.file_path), encoding='utf-8'))
            next(csv_reader)
            for index, row in enumerate(csv_reader):
                create_user = request.user
                attr = Attr.objects.get(attr_name=row[2])
                source = row[5]
                train_or_test = row[6]
                positive_or_negative = row[7]
                anomaly_time = row[4]
                anomaly_time = '-'.join(anomaly_time.split('/'))
                data_a = row[8]
                window = len(data_a.split(',')) - 1
                data_b = row[9]
                data_c = row[10]
                upload = f
                SampleSet.objects.create(
                    attr=attr,
                    source=source,
                    train_or_test=train_or_test,
                    positive_or_negative=positive_or_negative,
                    anomaly_time=anomaly_time,
                    data_a=data_a,
                    data_b=data_b,
                    data_c=data_c,
                    window=window,
                    upload=upload,
                    create_user=create_user,
                )
            f.sample_count = index + 1
            f.save()
            return_dict = build_ret_data(OP_SUCCESS, str("res"))
            return render_json(return_dict)
        except Exception as e:
            traceback.print_exc()
            return_dict = build_ret_data(THROW_EXP, str(e))
            return render_json(return_dict)

file_path = request.data['file']这是获取文件的关键。
后面是保存Field内容,读取csv文件内容,分析csv文件内容及插库处理。

相关文章

网友评论

      本文标题:vue antd admin结合django rest fram

      本文链接:https://www.haomeiwen.com/subject/pchonktx.html