优化文件上传

This commit is contained in:
不做码农 2022-01-02 17:40:19 +08:00
parent 55f655816a
commit 5171ed2408
4 changed files with 82 additions and 106 deletions

View File

@ -1,5 +1,6 @@
using Infrastructure; using Infrastructure;
using Infrastructure.Attribute; using Infrastructure.Attribute;
using Infrastructure.Extensions;
using Infrastructure.Model; using Infrastructure.Model;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
@ -96,16 +97,19 @@ namespace ZR.Admin.WebApi.Controllers
/// </summary> /// </summary>
/// <param name="formFile"></param> /// <param name="formFile"></param>
/// <param name="fileDir">存储目录</param> /// <param name="fileDir">存储目录</param>
/// <param name="fileName">文件名</param>
/// <param name="uploadType">上传类型 1、发送邮件</param> /// <param name="uploadType">上传类型 1、发送邮件</param>
/// <returns></returns> /// <returns></returns>
[HttpPost()] [HttpPost()]
[Verify] [Verify]
[ActionPermissionFilter(Permission = "common")] [ActionPermissionFilter(Permission = "common")]
public IActionResult UploadFile([FromForm(Name = "file")] IFormFile formFile, string fileDir = "uploads", int uploadType = 0) public IActionResult UploadFile([FromForm(Name = "file")] IFormFile formFile, string fileName = "", string fileDir = "uploads", int uploadType = 0)
{ {
if (formFile == null) throw new CustomException(ResultCode.PARAM_ERROR, "上传文件不能为空"); if (formFile == null) throw new CustomException(ResultCode.PARAM_ERROR, "上传文件不能为空");
string fileExt = Path.GetExtension(formFile.FileName); string fileExt = Path.GetExtension(formFile.FileName);
string fileName = FileUtil.HashFileName(Guid.NewGuid().ToString()).ToLower() + fileExt; string hashFileName = FileUtil.HashFileName(Guid.NewGuid().ToString()).ToLower();
fileName = (fileName.IsEmpty() ? hashFileName : fileName) + fileExt;
fileDir = fileDir.IsEmpty() ? "uploads" : fileDir;
string filePath = FileUtil.GetdirPath(fileDir); string filePath = FileUtil.GetdirPath(fileDir);
string finalFilePath = Path.Combine(WebHostEnvironment.WebRootPath, filePath, fileName); string finalFilePath = Path.Combine(WebHostEnvironment.WebRootPath, filePath, fileName);
finalFilePath = finalFilePath.Replace("\\", "/").Replace("//", "/"); finalFilePath = finalFilePath.Replace("\\", "/").Replace("//", "/");

View File

@ -1,11 +1,8 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using SqlSugar; using SqlSugar;
using Infrastructure;
using Infrastructure.Attribute; using Infrastructure.Attribute;
using Infrastructure.Enums; using Infrastructure.Enums;
using Infrastructure.Model; using Infrastructure.Model;
using Mapster;
using ZR.Admin.WebApi.Extensions;
using ZR.Admin.WebApi.Filters; using ZR.Admin.WebApi.Filters;
using ZR.Common; using ZR.Common;
using ZR.Model.System; using ZR.Model.System;
@ -66,66 +63,66 @@ namespace ZR.Admin.WebApi.Controllers
return SUCCESS(response); return SUCCESS(response);
} }
/// <summary> ///// <summary>
/// 添加文件存储 ///// 添加文件存储
/// </summary> ///// </summary>
/// <returns></returns> ///// <returns></returns>
[HttpPost] //[HttpPost]
[ActionPermissionFilter(Permission = "tool:file:add")] //[ActionPermissionFilter(Permission = "tool:file:add")]
[Log(Title = "文件存储", BusinessType = BusinessType.INSERT)] //[Log(Title = "文件存储", BusinessType = BusinessType.INSERT)]
public IActionResult AddSysFile([FromBody] SysFileDto parm) //public IActionResult AddSysFile([FromBody] SysFileDto parm)
{ //{
if (parm == null) // if (parm == null)
{ // {
throw new CustomException("请求参数错误"); // throw new CustomException("请求参数错误");
} // }
//从 Dto 映射到 实体 // //从 Dto 映射到 实体
var model = parm.Adapt<SysFile>().ToCreate(HttpContext); // var model = parm.Adapt<SysFile>().ToCreate(HttpContext);
var response = _SysFileService.Insert(model, it => new // var response = _SysFileService.Insert(model, it => new
{ // {
it.FileName, // it.FileName,
it.FileUrl, // it.FileUrl,
it.StorePath, // it.StorePath,
it.FileSize, // it.FileSize,
it.FileExt, // it.FileExt,
it.Create_by, // it.Create_by,
it.Create_time, // it.Create_time,
it.StoreType, // it.StoreType,
it.AccessUrl, // it.AccessUrl,
}); // });
return ToResponse(response); // return ToResponse(response);
} //}
/// <summary> ///// <summary>
/// 更新文件存储 ///// 更新文件存储
/// </summary> ///// </summary>
/// <returns></returns> ///// <returns></returns>
[HttpPut] //[HttpPut]
[ActionPermissionFilter(Permission = "tool:file:update")] //[ActionPermissionFilter(Permission = "tool:file:update")]
[Log(Title = "文件存储", BusinessType = BusinessType.UPDATE)] //[Log(Title = "文件存储", BusinessType = BusinessType.UPDATE)]
public IActionResult UpdateSysFile([FromBody] SysFileDto parm) //public IActionResult UpdateSysFile([FromBody] SysFileDto parm)
{ //{
if (parm == null) // if (parm == null)
{ // {
throw new CustomException("请求实体不能为空"); // throw new CustomException("请求实体不能为空");
} // }
//从 Dto 映射到 实体 // //从 Dto 映射到 实体
var model = parm.Adapt<SysFile>().ToUpdate(HttpContext); // var model = parm.Adapt<SysFile>().ToUpdate(HttpContext);
var response = _SysFileService.Update(w => w.Id == model.Id, it => new SysFile() // var response = _SysFileService.Update(w => w.Id == model.Id, it => new SysFile()
{ // {
//Update 字段映射 // //Update 字段映射
FileUrl = model.FileUrl, // FileUrl = model.FileUrl,
StorePath = model.StorePath, // StorePath = model.StorePath,
FileSize = model.FileSize, // FileSize = model.FileSize,
FileExt = model.FileExt, // FileExt = model.FileExt,
StoreType = model.StoreType, // StoreType = model.StoreType,
AccessUrl = model.AccessUrl, // AccessUrl = model.AccessUrl,
}); // });
return ToResponse(response); // return ToResponse(response);
} //}
/// <summary> /// <summary>
/// 删除文件存储 /// 删除文件存储

View File

@ -8,8 +8,8 @@
<!-- 上传提示 --> <!-- 上传提示 -->
<div class="el-upload__tip" slot="tip" v-if="showTip"> <div class="el-upload__tip" slot="tip" v-if="showTip">
请上传 请上传
<template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template> <span v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </span>
<template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template> <span v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </span>
的文件 的文件
</div> </div>
</el-upload> </el-upload>

View File

@ -20,14 +20,11 @@
<!-- 工具区域 --> <!-- 工具区域 -->
<el-row :gutter="10" class="mb8"> <el-row :gutter="10" class="mb8">
<el-col :span="1.5"> <el-col :span="1.5">
<el-button type="primary" v-hasPermi="['System:sysfile:add']" plain icon="el-icon-upload" size="mini" @click="handleAdd">上传文件</el-button> <el-button type="primary" v-hasPermi="['tool:file:add']" plain icon="el-icon-upload" size="mini" @click="handleAdd">上传文件</el-button>
</el-col> </el-col>
<!-- <el-col :span="1.5">
<el-button type="success" :disabled="single" v-hasPermi="['System:sysfile:update']" plain icon="el-icon-edit" size="mini" @click="handleUpdate">修改</el-button>
</el-col> -->
<el-col :span="1.5"> <el-col :span="1.5">
<el-button type="danger" :disabled="multiple" v-hasPermi="['System:sysfile:delete']" plain icon="el-icon-delete" size="mini" <el-button type="danger" :disabled="multiple" v-hasPermi="['tool:file:delete']" plain icon="el-icon-delete" size="mini" @click="handleDelete">
@click="handleDelete">删除</el-button> 删除</el-button>
</el-col> </el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
</el-row> </el-row>
@ -58,12 +55,12 @@
<el-table-column prop="fileSize" label="文件大小" align="center" :show-overflow-tooltip="true" /> <el-table-column prop="fileSize" label="文件大小" align="center" :show-overflow-tooltip="true" />
<el-table-column prop="fileExt" label="扩展名" align="center" :show-overflow-tooltip="true" width="80px" /> <el-table-column prop="fileExt" label="扩展名" align="center" :show-overflow-tooltip="true" width="80px" />
<el-table-column prop="storeType" label="存储类型" align="center" :formatter="storeTypeFormat" /> <el-table-column prop="storeType" label="存储类型" align="center" :formatter="storeTypeFormat" />
<el-table-column prop="create_by" label="操作人" align="center"/> <el-table-column prop="create_by" label="操作人" align="center" />
<el-table-column prop="create_time" label="创建日期" align="center" /> <el-table-column prop="create_time" label="创建日期" align="center" />
<el-table-column label="操作" align="center" width="200"> <el-table-column label="操作" align="center" width="200">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button v-hasPermi="['System:sysfile:view']" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button> <el-button type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
<el-button v-hasPermi="['System:sysfile:delete']" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button> <el-button v-hasPermi="['tool:file:delete']" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
@ -73,11 +70,11 @@
<el-dialog :title="title" :lock-scroll="false" :visible.sync="open" width="400px"> <el-dialog :title="title" :lock-scroll="false" :visible.sync="open" width="400px">
<el-form ref="form" :model="form" :rules="rules" label-width="135px" label-position="left"> <el-form ref="form" :model="form" :rules="rules" label-width="135px" label-position="left">
<el-row> <el-row>
<!-- <el-col :lg="12"> <el-col :lg="12">
<el-form-item label="自定文件名" prop="fileName"> <el-form-item label="文件名" prop="fileName">
<el-input v-model="form.fileName" placeholder="请输入文件名" /> <el-input v-model="form.fileName" placeholder="请输入文件名" />
</el-form-item> </el-form-item>
</el-col> --> </el-col>
<el-col :lg="24"> <el-col :lg="24">
<el-form-item label="存储类型" prop="storeType"> <el-form-item label="存储类型" prop="storeType">
<el-select v-model="form.storeType" placeholder="请选择存储类型" @change="handleSelectStore"> <el-select v-model="form.storeType" placeholder="请选择存储类型" @change="handleSelectStore">
@ -99,14 +96,14 @@
</el-col> </el-col>
<el-col :lg="24"> <el-col :lg="24">
<el-form-item label="上传文件" prop="accessUrl"> <el-form-item label="上传文件" prop="accessUrl">
<UploadFile v-model="form.accessUrl" :uploadUrl="uploadUrl" :fileType="[]" :limit="1" :fileSize="15" :data="{ 'fileDir' : form.storePath}" <UploadFile v-model="form.accessUrl" :uploadUrl="uploadUrl" :fileType="[]" :limit="1" :fileSize="15"
column="accessUrl" @input="handleUploadSuccess" /> :data="{ 'fileDir' : form.storePath, 'fileName': form.fileName}" column="accessUrl" @input="handleUploadSuccess" />
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-row> </el-row>
</el-form> </el-form>
<div slot="footer" class="dialog-footer" v-if="btnSubmitVisible"> <div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm"> </el-button> <el-button type="primary" @click="submitForm"> </el-button>
<el-button @click="cancel"> </el-button> <el-button @click="cancel"> </el-button>
</div> </div>
@ -153,7 +150,7 @@ import {
listSysfile, listSysfile,
// addSysfile, // addSysfile,
delSysfile, delSysfile,
updateSysfile, // updateSysfile,
getSysfile, getSysfile,
// exportSysfile, // exportSysfile,
} from "@/api/tool/file.js"; } from "@/api/tool/file.js";
@ -271,7 +268,7 @@ export default {
this.form = { this.form = {
fileName: undefined, fileName: undefined,
fileUrl: undefined, fileUrl: undefined,
storePath: "", storePath: "uploads",
fileSize: undefined, fileSize: undefined,
fileExt: undefined, fileExt: undefined,
storeType: 1, storeType: 1,
@ -320,20 +317,16 @@ export default {
}, },
/** 修改按钮操作 */ /** 修改按钮操作 */
handleView(row) { handleView(row) {
// this.reset();
const id = row.id || this.ids; const id = row.id || this.ids;
getSysfile(id).then((res) => { getSysfile(id).then((res) => {
const { code, data } = res; const { code, data } = res;
if (code == 200) { if (code == 200) {
this.openView = true; this.openView = true;
this.formView = data;
this.formView = {
...data,
};
} }
}); });
}, },
// //
handleUploadSuccess(columnName, filelist) { handleUploadSuccess(columnName, filelist) {
this.form[columnName] = filelist; this.form[columnName] = filelist;
}, },
@ -350,26 +343,8 @@ export default {
}, },
/** 提交按钮 */ /** 提交按钮 */
submitForm: function () { submitForm: function () {
this.$refs["form"].validate((valid) => {
if (valid) {
console.log(JSON.stringify(this.form));
if (this.form.id != undefined && this.title === "修改数据") {
updateSysfile(this.form)
.then((res) => {
this.msgSuccess("修改成功");
this.open = false; this.open = false;
this.getList(); this.getList();
})
.catch((err) => {
//TODO
});
} else {
this.open = false;
this.getList();
}
}
});
}, },
}, },
}; };