首页 > 其他分享 >前端VUE上传文件+后端.NET WebApi

前端VUE上传文件+后端.NET WebApi

时间:2024-11-18 16:42:13浏览次数:1  
标签:WebApi files VUE string getList value item param NET

前端:VUE

 

<template>
    <div v-loading="loading" element-loading-text="Loading...">
        <el-header class="order">
            <el-row class="top from" :gutter="20">
                <el-col :span="15">
                    <el-col class="datatime">
                        <el-cascader
                              v-model="value"
                              :options="options"
                              @change="changeDatatime"
                            ></el-cascader>
                    </el-col>
                    <el-col :span="19">
                        <el-date-picker class="time" v-model="param.startTime" type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间" @change="changeTime">
                        </el-date-picker>至
                        <el-date-picker class="time" v-model="param.endTime" type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间" @change="changeTime">
                        </el-date-picker>
                    </el-col>
                </el-col>
                <el-col :span="9" class="function">
                    <div class="upload-excel">
                    <input
                      ref="excel-upload-input"
                      class="excel-upload-input"
                      type="file"
                      accept=".xlsx, .xls"
                      @change="selectFile"
                    >
                    </div>
                    <el-button type="primary" @click="downloadExcel()">下载导入模板</el-button>
                    <el-button type="primary" @click="uploadExcel()">导入</el-button>
                    <el-button @click="refresh()">刷新</el-button>
                </el-col>
            </el-row>

            <div class="radio">
                <div class="state">
                    <span class="title">状态:</span>
                    <el-radio-group v-model="param.state" @change="changeState">
                        <el-radio label="-1">全部</el-radio>
                        <el-radio label="0">未验铅</el-radio>
                        <el-radio label="1">已验铅</el-radio>
                    </el-radio-group>
                </div>
            </div>

            <div class="btn">
                <div class="material">
                    封号:
                    <el-input placeholder="铅封号" size="small" v-model="param.sealNo" @input="changeCustom"></el-input>
                </div>
                <div class="custom" v-if="userIsShow">
                    承运商:
                    <el-input placeholder="承运商" size="small" v-model="param.carrierName" @input="changeCustom">
                        <template #suffix>
                            <i class="el-input__icon el-icon-search hand" @click="openCustom(4)"></i>
                        </template>
                    </el-input>
                </div>
            </div>
        </el-header>
        <el-main>
            <el-table :data="dataList" :header-cell-style="{background:'#F4F8FF'}" row-key="Id"
                :tree-props="{children: 'MaterialList', hasChildren: 'hasChildren'}" class="treeTable" @select="changeSelection" @select-all="changeSelectionAll">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column prop="Id" label="ID" type="" width="100">
                </el-table-column>
                <el-table-column prop="DeparturePort" label="起运港" type="" width="100">
                </el-table-column>
                <el-table-column prop="DestinationPort" label="目的港" type="" min-width="100" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="BoxType" label="箱型" min-width="100" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="ShipName" label="船名/航次" width="180" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="BookingNumber" label="订舱单号"  width="180">
                </el-table-column>
                <el-table-column prop="CntrNo" label="柜号" width="150">
                </el-table-column>
                <el-table-column prop="SealNo" label="封号" width="110" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="ProductName" label="品名" width="110">
                </el-table-column>
                <el-table-column prop="Tonnage" label="装箱吨数" width="100" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="Barge" label="驳船" width="150" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="SampleNumber" label="样号" width="150" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="CarrierName" label="承运商" width="150" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="Remark" label="备注" width="110" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="State" label="状态" width="100">
                    <template #default="scope">
                        <span class="errorColor" v-if="scope.row.State==0">未验铅</span>
                        <span class="linkColor"  v-else-if="scope.row.State==1">已验铅</span>
                    </template>
                </el-table-column>
                <el-table-column prop="SaveTime" label="保存时间" width="170">
                </el-table-column>
            </el-table>
            <div class="page clearFloat">
                <span class="currentData">当前共
                    <span class="dataNum">{{dataTotal}}</span> 条记录</span>
                <el-pagination background layout="prev, pager, next,sizes,jumper" :total="dataTotal" @size-change="handleSizeChange"
                 @current-change="handleCurrentChange" :page-sizes="[10, 20, 30, 40]">
                </el-pagination>
            </div>
        </el-main>
    </div>
    
    <el-dialog title="物料" v-model="materialShow" :destroy-on-close="true" :close-on-click-modal="false">
        <material-choose @material-choose="currentMaterial"></material-choose>
    </el-dialog>
    <el-dialog title="单位" v-model="customShow" :destroy-on-close="true" :close-on-click-modal="false">
        <custom-choose @custom-choose="currentCustom"></custom-choose>
    </el-dialog>
    <el-dialog title="车辆" v-model="vehicleShow" custom-class="headerDialog" :destroy-on-close="true" :close-on-click-modal="false">
        <vehicle-choose @vehicle-choose="currentVehicle"></vehicle-choose>
    </el-dialog>
    <el-dialog title="司机" v-model="driverShow" custom-class="headerDialog" :destroy-on-close="true" :close-on-click-modal="false">
        <driver-choose @driver-choose="currentDriver"></driver-choose>
    </el-dialog>
    
</template>

<script>
    import axios from 'axios';
    import customChoose from "@/components/BasicData/Custom"
    export default {
        inject: ['reload'],
        components:{
            "custom-choose":customChoose
        },
        data() {
            return {
                loading:false,

                param: {
                    organCode:'',
                    pageIndex: 1,
                    pageSize: 10,
                    state: '-1',
                    startTime: '',
                    endTime: '',
                    sealNo: '',
                    carrierCode:'',
                    carrierName:'',
                },
                time: [],
                dataList: [],
                dataTotal: 0,
                options: [{
                        value: '1',
                        label: '当日'
                    }, {
                        value: '2',
                        label: '当月'
                    }, {
                        value: '3',
                        label: '一周'
                    }, {
                        value: '4',
                        label: '一月'
                    }, {
                        value: '5',
                        label: '三月'
                    },
                    {
                        value: '6',
                        label: '半年'
                    },
                    {
                        value: '7',
                        label: '一年'
                    }
                ],
                value: '',
                codearr:[],
                organCode:'',
                userIsShow:true,
                userInfo:{},
                customNature: 1,
                customShow:false
                
            }
        },
        created() { //创建后挂载
            
        },
        mounted() {
            this.organCode=this.$store.state.OrganCode;
            this.param.organCode=this.$store.state.OrganCode;
            this.userInfo= this.$store.state.userInfo
            if(this.userInfo.UserIdentifier==7){
                this.userIsShow=false;
            }
            this.setDefault()
            this.getList()
        },
        methods: {
            async downloadExcel() {
                window.open(axios.defaults.baseURL+'/UpLoad/ExcelToTable/发货单模板.xlsx', '_blank');
                toastr.info("模板下载中...");
            },
            //上传
            uploadExcel() {        
                let that = this;
                console.log(that.userIsShow)
                console.log(that.param.carrierCode)
                if(that.userIsShow)
                {
                    if(that.param.carrierCode=='')
                    {
                        that.$message({
                            message: '请选择承运商!',
                        });
                        return;
                    }
                }
                
                this.$refs['excel-upload-input'].click()
            },
            // 点击文件选择-------------------------------
            selectFile(e) {                
              // 获取选择的文件列表
              const files = e.target.files
              if (files.length > 0) {
                this.uploadFiles(files[0])
              }
            },
            // 选择了文件后上传的方法,两处都用到了,所以封装了方法
            async uploadFiles(file) {
                let that = this;
                that.loading = true
                const formData = new FormData();
                formData.append('file', file);
                formData.append('code', that.param.carrierCode);
                formData.append('name', that.param.carrierName);
                
                that.$axios.DeliveryDetails.UploadExcel(formData).then(res => {
                    that.loading = false
                    if (res.errCode == 0) {
                        that.$message({
                            message: '上传成功!',
                        });
                    } else {
                        that.$message.error(res.errMsg);
                    }
                }).catch(err => {
                    that.loading = false
                    that.$message.error(err.errMsg);
                })
                
                this.reload()
            },

            refresh() {
                this.reload()
            },
            changeSelection(selection,row){
                this.codearr = selection
            },
            changeSelectionAll(selection){
                this.codearr = selection
            },
            changeDatatime(value) {
                let that = this;
                this.param.startTime = that.$base.getStartTime(value);
                this.param.endTime = that.$base.getDateNow() + " 23:59:59";
                that.getList();
            },
            setDefault() {
                var that = this;
                that.value = "2";
                this.param.startTime = that.$base.getStartTime(that.value);
                this.param.endTime = that.$base.getDateNow() + " 23:59:59";
            },

            getList() {
                let that = this;
                that.loading = true
                that.$axios.DeliveryDetails.GetList(that.param).then(res => {
                    that.loading = false
                    if (res.errCode == 0) {
                        that.dataList = res.result
                        that.dataTotal=res.totalCount
                    } else {
                        that.$message.error(res.errMsg);
                    }
                }).catch(err => {
                    that.loading = false
                    that.$message.error(err.errMsg);
                })
            },
            handleSizeChange(pageSize) {
                this.param.pageSize = pageSize
                this.getList()
            },
            handleCurrentChange(pageIndex) {
                this.param.pageIndex = pageIndex
                this.getList()
            },

            changeTime(val) {
                this.getList()
            },

            changeState(val) {
                this.getList()
            },
            changeCustom() {
                this.getList()
            },
            openCustom(nature) {
                this.customNature = nature
                this.customShow = true
            },
            currentCustom(row) {
                this.param.carrierCode = row.ThirdCode
                this.param.carrierName = row.Name
                this.customShow = false
                this.getList()
            },
        }
    }
</script>

<style scoped="scoped" lang="less">
    .el-header {
        padding: 24px;
        height: auto !important;
        .datatime {
            width: 90px !important;
            flex: 0 0 90px !important;
            padding-left: 0 !important;
        }
        .function {
            text-align: right;
        }

        .title {
            width: 42px;
            display: inline-block;
        }

        .type {
            margin-top: 12px;
            font-size: 14px;
            color: #595959;
            line-height: 22px;

            .el-checkbox-group {
                display: inline-block;
            }
        }

        .radio {
            width: 100%;
            font-size: 14px;
            color: #595959;
            line-height: 22px !important;
            height: 22px !important;
            margin-top: 15px;

            .state,
            .audit {
                display: inline-block;
            }

            .audit {
                margin-left: 12px;
            }
        }

        .btn {
            margin-top: 15px;

            .custom,
            .material {
                display: inline-block;

                .el-input {
                    margin-left: 8px;
                    width: 219px !important;
                }
                margin-right: 24px;
            }

            .material {
                
            }
        }

    }

    .el-main {
        padding-top: 0px;


    }

    .tree {
        margin-right: 12px;
        border: 1px solid #F4F8FF;
    }

    .topSpan {
        box-sizing: border-box;
        display: inline-block;
        width: 100%;
        height: 44px;
        line-height: 44px;
        background-color: #F4F8FF;
        padding-left: 28px;
        font-size: 14px;
    }
    
     .excel-upload-input {
        display: none;
        z-index: -9999;
      }
</style>

 

后端:WebApi

 

        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResponse UploadExcel()
        {
            try
            {
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
                HttpRequestBase httpRequestBase = httpContextBase.Request;//定义传统request对象
                HttpFileCollectionBase files = httpRequestBase.Files;
                string name = httpRequestBase.Form["name"];
                string code = httpRequestBase.Form["code"];
                if (files != null && files.Count > 0)
                {
                    string fullUpLoadPath = HttpContext.Current.Server.MapPath("~/UpLoad/ExcelToTable/");
                    //检查本地上传的物理路径是否存在,不存在则创建
                    if (!System.IO.Directory.Exists(fullUpLoadPath))
                    {
                        System.IO.Directory.CreateDirectory(fullUpLoadPath);
                    }

                    string fileSuffix = Path.GetExtension(files[0].FileName).ToLower();
                    string fileId = Guid.NewGuid().ToString();
                    string dateKey = DateTime.Now.ToString("yyyyMMddHHmmss");
                    string fileName = fullUpLoadPath + dateKey + fileSuffix;

                    if (fileSuffix!= ".xlsx" && fileSuffix != ".xls")
                    {
                        throw new Exception("请选择正确的格式文件");
                    }

                    files[0].SaveAs(fileName);


                    List<DeliveryDetailsVO> list  =  Tools.ExcelToData(fileName);
                    foreach (var item in list)
                    {
                        item.State = 0;
                        item.UserCode = loginUserInfo.UserCode;
                        item.UserName = loginUserInfo.UserName;
                        item.SaveTime = Tools.Now;
                        item.OrganCode = loginUserInfo.OrganCode;
                        if (!string.IsNullOrEmpty(code))
                        {
                            item.CarrierCode = code;
                            item.CarrierName = name;
                        }
                        else
                        {
                            var customTemp = customServices.GetCustomByUserCode(loginUserInfo.OrganCode, loginUserInfo.UserCode);
                            if (customTemp != null)
                            {
                                item.CarrierCode = customTemp.ThirdCode;
                                item.CarrierName = customTemp.Name;
                            }
                        }


                        string whereStr = $" and SealNo='{item.SealNo}'";
                        var deliveryDetailsTemp = deliveryDetailsServices.GetList(loginUserInfo.OrganCode, whereStr);
                        if (deliveryDetailsTemp.Count > 0)
                            continue;

                        deliveryDetailsServices.SaveEntity(item);
                    }
                }
                else
                {
                    throw new Exception("请选择要上传的文件");
                }

                return BaseApiResponse.ApiSuccess();
            }
            catch (Exception ex)
            {
                return BaseApiResponse.ApiError(ex.Message);
            }
        }

  

标签:WebApi,files,VUE,string,getList,value,item,param,NET
From: https://www.cnblogs.com/lijunzaizi/p/18553015

相关文章

  • vue+mockjs数据
    参考链接:https://blog.csdn.net/qi8023for/article/details/127618742=========第一种方法MSW:使用VueCLI的mock-server1、安装MSWnpminstallmsw2、工程下创建一个mocks文件夹和handlers.js和browser.js文件handlers.js定义MOCKAPI行为:import{rest}from'msw'ex......
  • 云原生周刊:Kubernetes v1.32 要来了
    开源项目推荐WoodpeckerWoodpecker是一款轻量级且功能强大的CI/CD引擎,以其高度可扩展性和易用性著称。它支持多种版本控制系统与编程语言,能够灵活适配不同开发流程,帮助团队实现高效的持续集成与交付。无论是个人项目还是大型团队,Woodpecker都能以简单的方式满足复杂的CI/CD......
  • Kubernetes内configmap的作用
    理解ConfigMap的基本概念定义:ConfigMap是Kubernetes用于存储非机密配置数据的一种资源对象。它允许你将配置信息与容器化应用程序分离,使得应用程序的配置更加灵活和易于管理。这些配置数据可以是环境变量、配置文件或者命令行参数等形式。类比传统配置方式:在......
  • ssm139选课排课系统的设计与开发+vue(论文+源码)_kaic
    摘 要互联网的普及,改变了人们正常的生活学习及消费习惯,而且也大大的节省了人们的时间,由于各种管理系统都再不断的增加,更方便了用户,也改良了很多的用户习惯。对于选课排课系统查询方面缺乏系统的管理方式,为提高选课排课系统效率,特开发了本选课排课系统。选课排课系统的设计......
  • 100 款支持 .NET 多版本的强大 WPF 控件库
    前言推荐一款集成了超过100款控件的流行XAML控件库,同时提供了一系列常用的.NET帮助类-CookPopularUI。它可以简化开发流程,让我们能够更加专注于核心业务逻辑的实现。让我们一起学习如何使用CookPopularUI,并详细了解其提供的丰富控件内容。项目介绍CookPopularUI不仅提供......
  • 基于SpringBoot + Vue的红色旅游网站的设计与实现(源码+文档+部署)
    文章目录1.前言2.系统演示录像3.论文参考4.代码运行展示图5.技术框架5.1SpringBoot技术介绍5.2Vue技术介绍6.可行性分析7.系统测试7.1系统测试的目的7.2系统功能测试8.数据库表设计9.代码参考10.数据库脚本11.找我做程序,有什么保障?12.联系我们1.前......
  • 基于SpringBoot + Vue的拖恒ERP-物资管理系统设计与实现(源码+文档+部署)
    文章目录1.前言2.系统演示录像3.论文参考4.代码运行展示图5.技术框架5.1SpringBoot技术介绍5.2Vue技术介绍6.可行性分析7.系统测试7.1系统测试的目的7.2系统功能测试8.数据库表设计9.代码参考10.数据库脚本11.找我做程序,有什么保障?12.联系我们1.前......
  • 基于SpringBoot + Vue的复兴村医疗管理系统设计与实现(源码+文档+部署)
    文章目录1.前言2.系统演示录像3.论文参考4.代码运行展示图5.技术框架5.1SpringBoot技术介绍5.2Vue技术介绍6.可行性分析7.系统测试7.1系统测试的目的7.2系统功能测试8.数据库表设计9.代码参考10.数据库脚本11.找我做程序,有什么保障?12.联系我们1.前......
  • 基于SpringBoot + Vue的儿童图书推荐系统设计与实现(源码+文档+部署)
    文章目录1.前言2.系统演示录像3.论文参考4.代码运行展示图5.技术框架5.1SpringBoot技术介绍5.2Vue技术介绍6.可行性分析7.系统测试7.1系统测试的目的7.2系统功能测试8.数据库表设计9.代码参考10.数据库脚本11.找我做程序,有什么保障?12.联系我们1.前......
  • Electron框架使用vue开发跨平台桌面工具应用-后台日志发送到前台和执行导入ZIP
    一、后台日志发送到前台首先在preload.js里面注册回调因为需要主窗口给vue页面发送,需要把窗口管理起来,不能直接写在backgroud.js里面。需要暴露出来所以编写了windowManager.js//windowManager.jsletmainWindow=null;//设置mainWindowexportfunctionsetMainWind......