<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">點(diǎn)擊上傳</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(
`當(dāng)前限制選擇1 個(gè)文件,本次選擇了 ${files.length} 個(gè)文件,共選擇了 ${
files.length + fileList.length
} 個(gè)文件`
);
},
},
};
</script>
<style scoped>
.line {
text-align: center;
}
</style>
后臺(tái)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}/";
//創(chuàng)建每日存儲(chǔ)文件夾
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");
}
//保存的文件名稱(以名稱和保存時(shí)間命名)
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", "上傳失敗,未檢測(cè)上傳的文件信息");
}
}
catch (Exception ex)
{
return IpResponse.Create(true, "0", "文件保存失敗,異常信息為:" + ex.Message);
}
}
聯(lián)系客服