优化文件上传

This commit is contained in:
不做码农 2022-03-26 20:23:47 +08:00
parent 494ccdbb88
commit 79f57c7ea5
9 changed files with 146 additions and 98 deletions

View File

@ -1,9 +1,4 @@
using System; using System.ComponentModel;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Infrastructure.Enums namespace Infrastructure.Enums
{ {
@ -30,5 +25,10 @@ namespace Infrastructure.Enums
[Description("腾讯云")] [Description("腾讯云")]
TENCENT = 3, TENCENT = 3,
/// <summary>
/// 七牛
/// </summary>
[Description("七牛云")]
QINIU = 4
} }
} }

View File

@ -1,5 +1,6 @@
using Infrastructure; using Infrastructure;
using Infrastructure.Attribute; using Infrastructure.Attribute;
using Infrastructure.Enums;
using Infrastructure.Extensions; using Infrastructure.Extensions;
using Infrastructure.Model; using Infrastructure.Model;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
@ -91,19 +92,53 @@ namespace ZR.Admin.WebApi.Controllers
/// <param name="formFile"></param> /// <param name="formFile"></param>
/// <param name="fileDir">存储目录</param> /// <param name="fileDir">存储目录</param>
/// <param name="fileName">自定义文件名</param> /// <param name="fileName">自定义文件名</param>
/// <param name="uploadType">上传类型 1、发送邮件</param> /// <param name="storeType">上传类型1、保存到本地 2、保存到阿里云</param>
/// <returns></returns> /// <returns></returns>
[HttpPost()] [HttpPost()]
[Verify] [Verify]
[ActionPermissionFilter(Permission = "common")] [ActionPermissionFilter(Permission = "common")]
public async Task<IActionResult> UploadFile([FromForm(Name = "file")] IFormFile formFile, string fileName = "", string fileDir = "uploads", int uploadType = 0) public async Task<IActionResult> UploadFile([FromForm(Name = "file")] IFormFile formFile, string fileName = "", string fileDir = "uploads", StoreType storeType = StoreType.LOCAL)
{ {
if (formFile == null) throw new CustomException(ResultCode.PARAM_ERROR, "上传文件不能为空"); if (formFile == null) throw new CustomException(ResultCode.PARAM_ERROR, "上传文件不能为空");
SysFile file = new();
string fileExt = Path.GetExtension(formFile.FileName);//文件后缀
double fileSize = Math.Round(formFile.Length / 1024.0, 2);//文件大小KB
string[] NotAllowedFileExtensions = new string[] { ".bat", ".exe", ".jar", ".js" };
int MaxContentLength = 15;
if (NotAllowedFileExtensions.Contains(fileExt))
{
return ToResponse(ResultCode.CUSTOM_ERROR, "上传失败,未经允许上传类型");
}
switch (storeType)
{
case StoreType.LOCAL:
file = await SysFileService.SaveFileToLocal(WebHostEnvironment.WebRootPath, fileName, fileDir, HttpContext.GetName(), formFile);
SysFile file = await SysFileService.SaveFileToLocal(WebHostEnvironment.WebRootPath, fileName, fileDir, HttpContext.GetName(), formFile); break;
case StoreType.ALIYUN:
if ((fileSize / 1024) > MaxContentLength)
{
return ToResponse(ResultCode.CUSTOM_ERROR, "上传文件过大,不能超过 " + MaxContentLength + " MB");
}
file = new(formFile.FileName, fileName, fileExt, fileSize + "kb", fileDir, HttpContext.GetName())
{
StoreType = (int)StoreType.ALIYUN,
FileType = formFile.ContentType
};
file = await SysFileService.SaveFileToAliyun(file, formFile);
if (file.Id <= 0) { return ToResponse(ApiResult.Error("阿里云连接失败")); }
break;
case StoreType.TENCENT:
break;
case StoreType.QINIU:
break;
default:
break;
}
return SUCCESS(new return SUCCESS(new
{ {
url = uploadType == 1 ? file.FileUrl : file.AccessUrl, url = file.AccessUrl,
fileName, fileName,
fileId = file.Id.ToString() fileId = file.Id.ToString()
}); });
@ -134,7 +169,7 @@ namespace ZR.Admin.WebApi.Controllers
{ {
return ToResponse(ResultCode.CUSTOM_ERROR, "上传文件过大,不能超过 " + MaxContentLength + " MB"); return ToResponse(ResultCode.CUSTOM_ERROR, "上传文件过大,不能超过 " + MaxContentLength + " MB");
} }
SysFile file = new(formFile.FileName, fileName, fileExt, fileSize + "kb", fileDir, "", HttpContext.GetName()) SysFile file = new(formFile.FileName, fileName, fileExt, fileSize + "kb", fileDir, HttpContext.GetName())
{ {
StoreType = (int)Infrastructure.Enums.StoreType.ALIYUN, StoreType = (int)Infrastructure.Enums.StoreType.ALIYUN,
FileType = formFile.ContentType FileType = formFile.ContentType

View File

@ -89,7 +89,7 @@ namespace ZR.CodeGenerator
//图片 //图片
sb.AppendLine(" <el-col :lg=\"24\">"); sb.AppendLine(" <el-col :lg=\"24\">");
sb.AppendLine($" <el-form-item label=\"{labelName}\" prop=\"{columnName}\">"); sb.AppendLine($" <el-form-item label=\"{labelName}\" prop=\"{columnName}\">");
sb.AppendLine($@" <UploadImage v-model=""form.{columnName}"" column=""{columnName}"" @input=""handleUploadSuccess"" />"); sb.AppendLine($@" <UploadImage v-model=""form.{columnName}"" :data=""{{ 'storeType' : 1}}"" column=""{columnName}"" @input=""handleUploadSuccess"" />");
sb.AppendLine(" </el-form-item>"); sb.AppendLine(" </el-form-item>");
sb.AppendLine(" </el-col>"); sb.AppendLine(" </el-col>");
} }

View File

@ -43,5 +43,25 @@ namespace ZR.Common
return System.Net.HttpStatusCode.BadRequest; return System.Net.HttpStatusCode.BadRequest;
} }
/// <summary>
/// 删除资源
/// </summary>
/// <param name="dirPath"></param>
/// <param name="bucketName"></param>
/// <returns></returns>
public static System.Net.HttpStatusCode DeleteFile(string dirPath, string bucketName = "")
{
if (string.IsNullOrEmpty(bucketName)) { bucketName = bucketName1; }
try
{
OssClient client = new(endpoint, accessKeyId, accessKeySecret);
DeleteObjectResult putObjectResult = client.DeleteObject(bucketName, dirPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return System.Net.HttpStatusCode.BadRequest;
}
} }
} }

View File

@ -72,14 +72,13 @@ namespace ZR.Model.System
public string AccessUrl { get; set; } public string AccessUrl { get; set; }
public SysFile() { } public SysFile() { }
public SysFile(string originFileName, string fileName, string ext, string fileSize, string storePath, string accessUrl,string create_by) public SysFile(string originFileName, string fileName, string ext, string fileSize, string storePath, string create_by)
{ {
StorePath = storePath; StorePath = storePath;
RealName = originFileName; RealName = originFileName;
FileName = fileName; FileName = fileName;
FileExt = ext; FileExt = ext;
FileSize = fileSize; FileSize = fileSize;
AccessUrl = accessUrl;
Create_by = create_by; Create_by = create_by;
Create_time = DateTime.Now; Create_time = DateTime.Now;
} }

View File

@ -51,14 +51,15 @@ namespace ZR.Service.System
using (var stream = new FileStream(finalFilePath, FileMode.Create)) using (var stream = new FileStream(finalFilePath, FileMode.Create))
{ {
await formFile.CopyToAsync(stream); await formFile.CopyToAsync(stream);//await 不能少
} }
string accessPath = string.Concat(OptionsSetting.Upload.UploadUrl, "/", filePath.Replace("\\", "/"), "/", fileName); string accessPath = string.Concat(OptionsSetting.Upload.UploadUrl, "/", filePath.Replace("\\", "/"), "/", fileName);
SysFile file = new(formFile.FileName, fileName, fileExt, fileSize + "kb", filePath, accessPath, userName) SysFile file = new(formFile.FileName, fileName, fileExt, fileSize + "kb", filePath, userName)
{ {
StoreType = (int)Infrastructure.Enums.StoreType.LOCAL, StoreType = (int)Infrastructure.Enums.StoreType.LOCAL,
FileType = formFile.ContentType, FileType = formFile.ContentType,
FileUrl = finalFilePath FileUrl = finalFilePath,
AccessUrl = accessPath
}; };
file.Id = await InsertFile(file); file.Id = await InsertFile(file);
return file; return file;

View File

@ -52,7 +52,7 @@ export default {
// , ['png', 'jpg', 'jpeg'] // , ['png', 'jpg', 'jpeg']
fileType: { fileType: {
type: Array, type: Array,
default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf', 'svga', 'json'] default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf', 'json']
}, },
// //
isShowTip: { isShowTip: {

View File

@ -1,7 +1,7 @@
<template> <template>
<div class="component-upload-image"> <div class="component-upload-image">
<el-upload list-type="picture-card" :action="uploadImgUrl" :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" <el-upload list-type="picture-card" :action="uploadImgUrl" :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload"
:on-exceed="handleExceed" :on-remove="handleRemove" :on-error="handleUploadError" name="file" :show-file-list="true" :limit="limit" :on-exceed="handleExceed" :on-remove="handleRemove" :on-error="handleUploadError" name="file" :show-file-list="true" :data="data" :limit="limit"
:file-list="fileList" :on-preview="handlePictureCardPreview" :on-progress="uploadProcess" :class="{hide: this.fileList.length >= this.limit}" :file-list="fileList" :on-preview="handlePictureCardPreview" :on-progress="uploadProcess" :class="{hide: this.fileList.length >= this.limit}"
:headers="headers"> :headers="headers">
<i slot="default" class="el-icon-plus"></i> <i slot="default" class="el-icon-plus"></i>
@ -20,7 +20,7 @@
</template> </template>
<script> <script>
import { getToken } from "@/utils/auth"; import { getToken } from '@/utils/auth'
export default { export default {
props: { props: {
@ -28,158 +28,162 @@ export default {
// //
limit: { limit: {
type: Number, type: Number,
default: 1, default: 1
}, },
column: [String], column: [String],
// //
uploadUrl: { uploadUrl: {
type: String, type: String,
default: process.env.VUE_APP_UPLOAD_URL ?? "/Common/UploadFile", default: process.env.VUE_APP_UPLOAD_URL ?? '/Common/UploadFile'
}, },
// , ['png', 'jpg', 'jpeg'] // , ['png', 'jpg', 'jpeg']
fileType: { fileType: {
type: Array, type: Array,
default: () => ["png", "jpg", "jpeg", "webp"], default: () => ['png', 'jpg', 'jpeg', 'webp']
}, },
// (MB) // (MB)
fileSize: { fileSize: {
type: Number, type: Number,
default: 5, default: 5
}, },
// //
showInput: false, showInput: false,
// //
isShowTip: { isShowTip: {
type: Boolean, type: Boolean,
default: true, default: true
}, },
//
data: {
type: Object
}
}, },
data() { data() {
return { return {
dialogImageUrl: "", dialogImageUrl: '',
dialogVisible: false, dialogVisible: false,
hideUpload: false, hideUpload: false,
uploadImgUrl: process.env.VUE_APP_BASE_API + this.uploadUrl, // uploadImgUrl: process.env.VUE_APP_BASE_API + this.uploadUrl, //
headers: { headers: {
Authorization: "Bearer " + getToken(), Authorization: 'Bearer ' + getToken()
}, },
imageUrl: "", imageUrl: '',
fileList: [], fileList: []
}; }
}, },
watch: { watch: {
// v-model // v-model
value: { value: {
immediate: true, immediate: true,
deep: true, deep: true,
handler: function (val) { handler: function(val) {
if (val) { if (val) {
// //
const list = Array.isArray(val) ? val : this.value.split(","); const list = Array.isArray(val) ? val : this.value.split(',')
// //
this.fileList = list.map((item) => { this.fileList = list.map((item) => {
if (typeof item === "string") { if (typeof item === 'string') {
// if (item.indexOf(this.baseUrl) === -1) { // if (item.indexOf(this.baseUrl) === -1) {
// item = { name: this.baseUrl + item, url: this.baseUrl + item }; // item = { name: this.baseUrl + item, url: this.baseUrl + item };
// } else { // } else {
item = { name: item, url: item }; item = { name: item, url: item }
// } // }
} }
return item; return item
}); })
} else { } else {
this.fileList = []; this.fileList = []
return []; return []
} }
}, }
}, }
}, },
computed: { computed: {
// //
showTip() { showTip() {
return this.isShowTip && (this.fileType || this.fileSize); return this.isShowTip && (this.fileType || this.fileSize)
}, }
}, },
methods: { methods: {
// //
handleRemove(file, fileList) { handleRemove(file, fileList) {
const findex = this.fileList.map((f) => f.name).indexOf(file.name); const findex = this.fileList.map((f) => f.name).indexOf(file.name)
if (findex > -1) { if (findex > -1) {
this.fileList.splice(findex, 1); this.fileList.splice(findex, 1)
this.$emit("input", this.column, this.listToString(this.fileList)); this.$emit('input', this.column, this.listToString(this.fileList))
} }
}, },
// //
handleUploadSuccess(res) { handleUploadSuccess(res) {
console.log(res); console.log(res)
if (res.code != 200) { if (res.code != 200) {
this.msgError(`上传失败,原因:${res.msg}!`); this.msgError(`上传失败,原因:${res.msg}!`)
return; return
} }
this.fileList.push({ name: res.data.fileName, url: res.data.url }); this.fileList.push({ name: res.data.fileName, url: res.data.url })
this.$emit(`input`, this.column, this.listToString(this.fileList)); this.$emit(`input`, this.column, this.listToString(this.fileList))
}, },
// loading // loading
handleBeforeUpload(file) { handleBeforeUpload(file) {
let isImg = false; let isImg = false
if (this.fileType.length) { if (this.fileType.length) {
let fileExtension = ""; let fileExtension = ''
if (file.name.lastIndexOf(".") > -1) { if (file.name.lastIndexOf('.') > -1) {
fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1); fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
} }
isImg = this.fileType.some((type) => { isImg = this.fileType.some((type) => {
if (file.type.indexOf(type) > -1) return true; if (file.type.indexOf(type) > -1) return true
if (fileExtension && fileExtension.indexOf(type) > -1) return true; if (fileExtension && fileExtension.indexOf(type) > -1) return true
return false; return false
}); })
} else { } else {
isImg = file.type.indexOf("image") > -1; isImg = file.type.indexOf('image') > -1
} }
if (!isImg) { if (!isImg) {
this.msgError( this.msgError(
`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!` `文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`
); )
return false; return false
} }
if (this.fileSize) { if (this.fileSize) {
const isLt = file.size / 1024 / 1024 < this.fileSize; const isLt = file.size / 1024 / 1024 < this.fileSize
if (!isLt) { if (!isLt) {
this.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`); this.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`)
return false; return false
} }
} }
}, },
// //
handleExceed() { handleExceed() {
this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`); this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`)
}, },
// //
handlePictureCardPreview(file) { handlePictureCardPreview(file) {
this.dialogImageUrl = file.url; this.dialogImageUrl = file.url
this.dialogVisible = true; this.dialogVisible = true
}, },
// //
listToString(list, separator) { listToString(list, separator) {
let strs = ""; let strs = ''
separator = separator || ","; separator = separator || ','
for (let i in list) { for (const i in list) {
strs += list[i].url.replace(this.baseUrl, "") + separator; strs += list[i].url.replace(this.baseUrl, '') + separator
} }
return strs != "" ? strs.substr(0, strs.length - 1) : ""; return strs != '' ? strs.substr(0, strs.length - 1) : ''
}, },
handleUploadError() { handleUploadError() {
this.$message({ this.$message({
type: "error", type: 'error',
message: "上传失败", message: '上传失败'
}); })
}, },
// //
uploadProcess(event, file, fileList) { uploadProcess(event, file, fileList) {
console.log("上传进度" + file.percentage); console.log('上传进度' + file.percentage)
}, }
}, }
}; }
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">

View File

@ -100,8 +100,8 @@
</el-col> </el-col>
<el-col :lg="24"> <el-col :lg="24">
<el-form-item prop="accessUrl"> <el-form-item prop="accessUrl">
<UploadFile ref="upload" v-model="form.accessUrl" :uploadUrl="uploadUrl" :fileType="[]" :limit="5" :fileSize="15" :drag="true" <UploadFile ref="upload" v-model="form.accessUrl" :fileType="[]" :limit="5" :fileSize="15" :drag="true"
:data="{ 'fileDir' : form.storePath, 'fileName': form.fileName}" :autoUpload="false" column="accessUrl" :data="{ 'fileDir' : form.storePath, 'fileName': form.fileName, 'storeType': form.storeType}" :autoUpload="false" column="accessUrl"
@input="handleUploadSuccess" /> @input="handleUploadSuccess" />
</el-form-item> </el-form-item>
</el-col> </el-col>
@ -208,8 +208,8 @@ export default {
{ dictLabel: '本地存储', dictValue: 1 }, { dictLabel: '本地存储', dictValue: 1 },
{ dictLabel: '阿里云存储', dictValue: 2 } { dictLabel: '阿里云存储', dictValue: 2 }
], ],
// // 1 2
uploadUrl: '/common/uploadFile', storeType: 0,
fileType: [], fileType: [],
// //
dataList: [], dataList: [],
@ -240,17 +240,6 @@ export default {
// //
this.getList() this.getList()
}, },
watch: {
'form.storeType': {
handler: function(val) {
if (val == 1) {
this.uploadUrl = '/common/uploadFile'
} else if (val == 2) {
this.uploadUrl = '/common/UploadFileAliyun'
}
}
}
},
methods: { methods: {
// //
getList() { getList() {