這兩種方式需要根據不同的業務才進行採用
這次用.Net6.0+Vue3來實現一個資料匯入的功能
接下來分別用程式碼來實現這兩種方式
[DisableRequestSizeLimit] [HttpPost] public IActionResult Upload() { var files = Request.Form.Files; long size = files.Sum(f => f.Length); string contentRootPath = AppContext.BaseDirectory; List<string> filenames = new List<string>(); foreach (IFormFile formFile in files) { if (formFile.Length > 0) { string fileExt = Path.GetExtension(formFile.FileName); long fileSize = formFile.Length; string newFileName = System.Guid.NewGuid().ToString() + fileExt; var filePath = contentRootPath + "/fileUpload/"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } using (var stream = new FileStream(filePath + newFileName, FileMode.Create)) { formFile.CopyTo(stream); } filenames.Add(newFileName); } } return Ok(filenames); }
這裡只是上傳檔案分了兩步走,第一步把檔案上傳到伺服器,第二步呼叫介面把返回的檔案路徑傳送給後臺進行資料儲存
/// <summary> /// 上傳檔案資料 /// </summary> /// <param name="uploadStuInfoInput"></param> /// <returns></returns> [HttpPut] public IActionResult Put(DataInput uploadStuInfoInput) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fileUpload", uploadStuInfoInput.filePath); if (!System.IO.File.Exists(filePath)) { return BadRequest("匯入失敗,檔案不存在!"); } var row = MiniExcelLibs.MiniExcel.Query<CompanyImportInput>(filePath).ToList(); companies.AddRange(row.Select(x => new Company { Name = x.名稱, Address = x.地址 })); return Ok("匯入成功!"); }
<el-table :data="state.tableData.data"> <el-table-column v-for="item in state.colunm" :prop="item.key" :key="item.key" :label="item.lable"> </el-table-column> </el-table> <div class='block flex justify-end' v-if='state.tableData.total > 0'> <el-pagination v-model:currentPage="state.searchInput.PageIndex" v-model:page-size="state.searchInput.PageSize" :page-sizes="[10, 50, 200, 1000]" layout="total, sizes, prev, pager, next, jumper" @size-change="getData" @current-change="getData" :total="state.tableData.total" /> </div>
const getData = () => { axios.get('/Company', { params: state.searchInput }).then(function (response) { state.tableData = response.data; }) }
[HttpGet] public dynamic Get([FromQuery] SelectInput selectInput) { return new { total = companies.Count(), data = companies.Skip((selectInput.pageIndex - 1) * selectInput.pageSize).Take(selectInput.pageSize).ToList() }; }
import FileUpload from '@/components/FileUpload.vue';
並繫結子頁面回撥方法fileUploadchildClick
<FileUpload ref="fileUpload" @childClick="fileUploadchildClick" accept=".xlsx" title="上傳檔案"></FileUpload>
<el-dialog :close-on-click-modal="false" v-model="state.dialogVisible" :title="title" width="40%"> <el-form :model='state.formData' label-width='130px' class='dialogForm'> <el-upload class='upload-demo' :limit="1" drag :accept='accept' :file-list='state.fileList' :show-file-list='true' :on-success='fileUploadEnd' :action='fileUploadUrl()'> <i class='el-icon-upload'></i> <div class='el-upload__text'>將檔案拖到此處,或<em>點選上傳</em></div> <div class='el-upload__tip'>請選擇({{ accept }})檔案</div> </el-upload> <div> <el-form-item> <el-button type='primary' @click='submit'>匯入</el-button> <el-button @click='cancel'>取消</el-button> </el-form-item> </div> </el-form> </el-dialog>
選擇檔案成功回撥方法
const fileUploadEnd = (response, file) => { state.fileresponse = file.name; state.formData.filePath = response[0]; if (state.fileList.length > 0) { state.fileList.splice(0, 1); } }
const submit = () => { if (state.formData.filePath == '') { ElMessage.error('請選擇上傳的檔案') return; } context.emit('childClick', state.formData) }
const fileUploadchildClick = (e) => { axios.put('/Company', { filePath: e.filePath, }).then(function (response) { if (response.status == 200) { ElMessage.success(response.data); fileUpload.value.cancel(); getData(); } else { ElMessage.error(response.data) } }) }
/// <summary> /// 上傳檔案資料 /// </summary> /// <param name="uploadStuInfoInput"></param> /// <returns></returns> [HttpPut] public IActionResult Put(DataInput uploadStuInfoInput) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fileUpload", uploadStuInfoInput.filePath); if (!System.IO.File.Exists(filePath)) { return BadRequest("匯入失敗,檔案不存在!"); } var row = MiniExcelLibs.MiniExcel.Query<CompanyImportInput>(filePath).ToList(); companies.AddRange(row.Select(x => new Company { Name = x.名稱, Address = x.地址 })); return Ok("匯入成功!");
}
import DataUpload from '@/components/DataUpload.vue';
並繫結子頁面回撥方法dataUploadchildClick
<DataUpload ref="dataUpload" @childClick="dataUploadchildClick" accept=".xlsx" title="上傳資料"></DataUpload>
<el-dialog :close-on-click-modal="false" v-model="state.dialogVisible" :title="title" width="50%"> <el-upload class="upload-demo" :action='accept' drag :auto-upload="false" :on-change="uploadChange" :limit="1"> <i class="el-icon-upload"></i> <div class="el-upload__text">將檔案拖到此處,或<em>點選上傳</em></div> </el-upload> <div> <el-form-item> <el-button @click='submit'>確認匯入</el-button> </el-form-item> </div> <el-table :data="state.tableData.data"> <el-table-column v-for="item in state.colunm" :prop="item.key" :key="item.key" :label="item.lable"> </el-table-column> </el-table> <div class='block flex justify-end' v-if='state.tableData.total > 0'> <el-pagination v-model:currentPage="state.searchInput.PageIndex" v-model:page-size="state.searchInput.PageSize" :page-sizes="[10, 50, 200, 1000]" layout="total, sizes, prev, pager, next, jumper" @size-change="getData" @current-change="getData" :total="state.tableData.total" /> </div> </el-dialog>
const uploadChange = async (file) => { let dataBinary = await readFile(file.raw) let workBook = XLSX.read(dataBinary, { type: 'binary', cellDates: true }) let workSheet = workBook.Sheets[workBook.SheetNames[0]] let data: any = XLSX.utils.sheet_to_json(workSheet) let tHeader = state.colunm.map(obj => obj.lable) let filterVal = state.colunm.map(obj => obj.key) tHeader.map(val => filterVal.map(obj => val[obj])) const tempData: any = []; data.forEach((value) => { const ob = {}; tHeader.forEach((item, index) => { ob[filterVal[index]] = value[item].toString(); }) tempData.push(ob); }) state.tempTableData = tempData; getData(); }
const getData = () => { const tempData: any = []; state.tempTableData.forEach((value, index) => { if (index >= ((state.searchInput.PageIndex - 1) * state.searchInput.PageSize) && index < ((state.searchInput.PageIndex) * state.searchInput.PageSize)) { tempData.push(value); } }); state.tableData.data = tempData; state.tableData.total = state.tempTableData.length; }
const submit = () => { context.emit('childClick', state.tempTableData) }
const dataUploadchildClick = (data) => { axios.post('/Company', data) .then(function (response) { if (response.status == 200) { ElMessage.success(response.data); dataUpload.value.cancel(); getData(); } else { ElMessage.error(response.data) } }) }
/// 上傳資料 /// </summary> /// <param name="uploadStuInfoInput"></param> /// <returns></returns> [HttpPost] public IActionResult Post(List<Company> companiesInput) { companies.AddRange(companiesInput); return Ok("儲存成功!"); }
最後關於這個資料匯入的功能就完成了,程式碼中有很多得虛擬碼,而且很多功能還待完善,後續再進行補充
附上git地址:https://gitee.com/wyf854861085/file-upload.git
Git演示圖: