<template> <div class="app-container"> <el-form ref="form" :model="form" :rules="rules2" label-width="120px"> <el-upload class="upload-demo" action="http://localhost:12345/api/test/upload" accept=".pdf" multiple :limit="1" :on-exceed="handleExceed" :file-list="fileList" > <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传pdf文件,且不超过10M</div> </el-upload> </el-form> </div> </template> <script> export default { data() { return { fileList: [], form: {}, }; }, methods: { handleExceed(files, fileList) { this.$message.warning( `当前限制选择1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${ files.length + fileList.length } 个文件` ); }, }, }; </script> <style scoped> .line { text-align: center; } </style> 后台core api接口 [HttpPost("upload")] public async Task<IpResponse> upload(IFormFile file) { var path = Directory.GetCurrentDirectory(); var currentDate = DateTime.Now; string webRootPath = Directory.GetCurrentDirectory(); try { var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/"; //创建每日存储文件夹 if (!Directory.Exists(webRootPath + filePath)) { Directory.CreateDirectory(webRootPath + filePath); } if (file != null) { //文件后缀 var fileExtension = Path.GetExtension(file.FileName);//获取文件格式,拓展名 //判断文件大小 var fileSize = file.Length; if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b) { return IpResponse.Create(true, "0", "上传的文件不能大于10M"); } //保存的文件名称(以名称和保存时间命名) var saveName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + fileExtension; //文件保存 using (var fs = System.IO.File.Create(webRootPath + filePath + saveName)) { file.CopyTo(fs); fs.Flush(); } //完整的文件路径 var completeFilePath = Path.Combine(filePath, saveName); return IpResponse.Create(true, "0", "上传成功"); } else { return IpResponse.Create(true, "0", "上传失败,未检测上传的文件信息"); } } catch (Exception ex) { return IpResponse.Create(true, "0", "文件保存失败,异常信息为:" + ex.Message); } } |
|