优化文件上传
This commit is contained in:
parent
494ccdbb88
commit
79f57c7ea5
@ -1,9 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Infrastructure.Enums
|
||||
{
|
||||
@ -30,5 +25,10 @@ namespace Infrastructure.Enums
|
||||
[Description("腾讯云")]
|
||||
TENCENT = 3,
|
||||
|
||||
/// <summary>
|
||||
/// 七牛
|
||||
/// </summary>
|
||||
[Description("七牛云")]
|
||||
QINIU = 4
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
using Infrastructure;
|
||||
using Infrastructure.Attribute;
|
||||
using Infrastructure.Enums;
|
||||
using Infrastructure.Extensions;
|
||||
using Infrastructure.Model;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
@ -91,19 +92,53 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
/// <param name="formFile"></param>
|
||||
/// <param name="fileDir">存储目录</param>
|
||||
/// <param name="fileName">自定义文件名</param>
|
||||
/// <param name="uploadType">上传类型 1、发送邮件</param>
|
||||
/// <param name="storeType">上传类型1、保存到本地 2、保存到阿里云</param>
|
||||
/// <returns></returns>
|
||||
[HttpPost()]
|
||||
[Verify]
|
||||
[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, "上传文件不能为空");
|
||||
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
|
||||
{
|
||||
url = uploadType == 1 ? file.FileUrl : file.AccessUrl,
|
||||
url = file.AccessUrl,
|
||||
fileName,
|
||||
fileId = file.Id.ToString()
|
||||
});
|
||||
@ -134,7 +169,7 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
{
|
||||
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,
|
||||
FileType = formFile.ContentType
|
||||
|
||||
@ -89,7 +89,7 @@ namespace ZR.CodeGenerator
|
||||
//图片
|
||||
sb.AppendLine(" <el-col :lg=\"24\">");
|
||||
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-col>");
|
||||
}
|
||||
|
||||
@ -43,5 +43,25 @@ namespace ZR.Common
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -72,14 +72,13 @@ namespace ZR.Model.System
|
||||
public string AccessUrl { get; set; }
|
||||
|
||||
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;
|
||||
RealName = originFileName;
|
||||
FileName = fileName;
|
||||
FileExt = ext;
|
||||
FileSize = fileSize;
|
||||
AccessUrl = accessUrl;
|
||||
Create_by = create_by;
|
||||
Create_time = DateTime.Now;
|
||||
}
|
||||
|
||||
@ -51,14 +51,15 @@ namespace ZR.Service.System
|
||||
|
||||
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);
|
||||
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,
|
||||
FileType = formFile.ContentType,
|
||||
FileUrl = finalFilePath
|
||||
FileUrl = finalFilePath,
|
||||
AccessUrl = accessPath
|
||||
};
|
||||
file.Id = await InsertFile(file);
|
||||
return file;
|
||||
|
||||
@ -52,7 +52,7 @@ export default {
|
||||
// 文件类型, 例如['png', 'jpg', 'jpeg']
|
||||
fileType: {
|
||||
type: Array,
|
||||
default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf', 'svga', 'json']
|
||||
default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf', 'json']
|
||||
},
|
||||
// 是否显示提示
|
||||
isShowTip: {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="component-upload-image">
|
||||
<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}"
|
||||
:headers="headers">
|
||||
<i slot="default" class="el-icon-plus"></i>
|
||||
@ -20,7 +20,7 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { getToken } from "@/utils/auth";
|
||||
import { getToken } from '@/utils/auth'
|
||||
|
||||
export default {
|
||||
props: {
|
||||
@ -28,158 +28,162 @@ export default {
|
||||
// 图片数量限制
|
||||
limit: {
|
||||
type: Number,
|
||||
default: 1,
|
||||
default: 1
|
||||
},
|
||||
column: [String],
|
||||
// 上传地址
|
||||
uploadUrl: {
|
||||
type: String,
|
||||
default: process.env.VUE_APP_UPLOAD_URL ?? "/Common/UploadFile",
|
||||
default: process.env.VUE_APP_UPLOAD_URL ?? '/Common/UploadFile'
|
||||
},
|
||||
// 文件类型, 例如['png', 'jpg', 'jpeg']
|
||||
fileType: {
|
||||
type: Array,
|
||||
default: () => ["png", "jpg", "jpeg", "webp"],
|
||||
default: () => ['png', 'jpg', 'jpeg', 'webp']
|
||||
},
|
||||
// 大小限制(MB)
|
||||
fileSize: {
|
||||
type: Number,
|
||||
default: 5,
|
||||
default: 5
|
||||
},
|
||||
//显示手动输入地址
|
||||
// 显示手动输入地址
|
||||
showInput: false,
|
||||
// 是否显示提示
|
||||
isShowTip: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
default: true
|
||||
},
|
||||
// 上传携带的参数
|
||||
data: {
|
||||
type: Object
|
||||
}
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
dialogImageUrl: "",
|
||||
dialogImageUrl: '',
|
||||
dialogVisible: false,
|
||||
hideUpload: false,
|
||||
uploadImgUrl: process.env.VUE_APP_BASE_API + this.uploadUrl, // 上传的图片服务器地址
|
||||
headers: {
|
||||
Authorization: "Bearer " + getToken(),
|
||||
Authorization: 'Bearer ' + getToken()
|
||||
},
|
||||
imageUrl: "",
|
||||
fileList: [],
|
||||
};
|
||||
imageUrl: '',
|
||||
fileList: []
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
//监听 v-model 的值
|
||||
// 监听 v-model 的值
|
||||
value: {
|
||||
immediate: true,
|
||||
deep: true,
|
||||
handler: function (val) {
|
||||
handler: function(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) => {
|
||||
if (typeof item === "string") {
|
||||
if (typeof item === 'string') {
|
||||
// if (item.indexOf(this.baseUrl) === -1) {
|
||||
// item = { name: this.baseUrl + item, url: this.baseUrl + item };
|
||||
// } else {
|
||||
item = { name: item, url: item };
|
||||
item = { name: item, url: item }
|
||||
// }
|
||||
}
|
||||
return item;
|
||||
});
|
||||
return item
|
||||
})
|
||||
} else {
|
||||
this.fileList = [];
|
||||
return [];
|
||||
this.fileList = []
|
||||
return []
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
computed: {
|
||||
// 是否显示提示
|
||||
showTip() {
|
||||
return this.isShowTip && (this.fileType || this.fileSize);
|
||||
},
|
||||
return this.isShowTip && (this.fileType || this.fileSize)
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
// 删除图片
|
||||
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) {
|
||||
this.fileList.splice(findex, 1);
|
||||
this.$emit("input", this.column, this.listToString(this.fileList));
|
||||
this.fileList.splice(findex, 1)
|
||||
this.$emit('input', this.column, this.listToString(this.fileList))
|
||||
}
|
||||
},
|
||||
//上传成功回调
|
||||
// 上传成功回调
|
||||
handleUploadSuccess(res) {
|
||||
console.log(res);
|
||||
console.log(res)
|
||||
if (res.code != 200) {
|
||||
this.msgError(`上传失败,原因:${res.msg}!`);
|
||||
return;
|
||||
this.msgError(`上传失败,原因:${res.msg}!`)
|
||||
return
|
||||
}
|
||||
this.fileList.push({ name: res.data.fileName, url: res.data.url });
|
||||
this.$emit(`input`, this.column, this.listToString(this.fileList));
|
||||
this.fileList.push({ name: res.data.fileName, url: res.data.url })
|
||||
this.$emit(`input`, this.column, this.listToString(this.fileList))
|
||||
},
|
||||
// 上传前loading加载
|
||||
handleBeforeUpload(file) {
|
||||
let isImg = false;
|
||||
let isImg = false
|
||||
if (this.fileType.length) {
|
||||
let fileExtension = "";
|
||||
if (file.name.lastIndexOf(".") > -1) {
|
||||
fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
|
||||
let fileExtension = ''
|
||||
if (file.name.lastIndexOf('.') > -1) {
|
||||
fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
|
||||
}
|
||||
isImg = this.fileType.some((type) => {
|
||||
if (file.type.indexOf(type) > -1) return true;
|
||||
if (fileExtension && fileExtension.indexOf(type) > -1) return true;
|
||||
return false;
|
||||
});
|
||||
if (file.type.indexOf(type) > -1) return true
|
||||
if (fileExtension && fileExtension.indexOf(type) > -1) return true
|
||||
return false
|
||||
})
|
||||
} else {
|
||||
isImg = file.type.indexOf("image") > -1;
|
||||
isImg = file.type.indexOf('image') > -1
|
||||
}
|
||||
|
||||
if (!isImg) {
|
||||
this.msgError(
|
||||
`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
|
||||
);
|
||||
return false;
|
||||
`文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`
|
||||
)
|
||||
return false
|
||||
}
|
||||
if (this.fileSize) {
|
||||
const isLt = file.size / 1024 / 1024 < this.fileSize;
|
||||
const isLt = file.size / 1024 / 1024 < this.fileSize
|
||||
if (!isLt) {
|
||||
this.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
|
||||
return false;
|
||||
this.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
},
|
||||
// 文件个数超出
|
||||
handleExceed() {
|
||||
this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
|
||||
this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`)
|
||||
},
|
||||
// 预览
|
||||
handlePictureCardPreview(file) {
|
||||
this.dialogImageUrl = file.url;
|
||||
this.dialogVisible = true;
|
||||
this.dialogImageUrl = file.url
|
||||
this.dialogVisible = true
|
||||
},
|
||||
// 对象转成指定字符串分隔
|
||||
listToString(list, separator) {
|
||||
let strs = "";
|
||||
separator = separator || ",";
|
||||
for (let i in list) {
|
||||
strs += list[i].url.replace(this.baseUrl, "") + separator;
|
||||
let strs = ''
|
||||
separator = separator || ','
|
||||
for (const i in list) {
|
||||
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() {
|
||||
this.$message({
|
||||
type: "error",
|
||||
message: "上传失败",
|
||||
});
|
||||
type: 'error',
|
||||
message: '上传失败'
|
||||
})
|
||||
},
|
||||
// 上传进度
|
||||
uploadProcess(event, file, fileList) {
|
||||
console.log("上传进度" + file.percentage);
|
||||
},
|
||||
},
|
||||
};
|
||||
console.log('上传进度' + file.percentage)
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
|
||||
@ -100,8 +100,8 @@
|
||||
</el-col>
|
||||
<el-col :lg="24">
|
||||
<el-form-item prop="accessUrl">
|
||||
<UploadFile ref="upload" v-model="form.accessUrl" :uploadUrl="uploadUrl" :fileType="[]" :limit="5" :fileSize="15" :drag="true"
|
||||
:data="{ 'fileDir' : form.storePath, 'fileName': form.fileName}" :autoUpload="false" column="accessUrl"
|
||||
<UploadFile ref="upload" v-model="form.accessUrl" :fileType="[]" :limit="5" :fileSize="15" :drag="true"
|
||||
:data="{ 'fileDir' : form.storePath, 'fileName': form.fileName, 'storeType': form.storeType}" :autoUpload="false" column="accessUrl"
|
||||
@input="handleUploadSuccess" />
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
@ -208,8 +208,8 @@ export default {
|
||||
{ dictLabel: '本地存储', dictValue: 1 },
|
||||
{ dictLabel: '阿里云存储', dictValue: 2 }
|
||||
],
|
||||
// 上传文件地址
|
||||
uploadUrl: '/common/uploadFile',
|
||||
// 存储类型 1、本地 2、阿里云
|
||||
storeType: 0,
|
||||
fileType: [],
|
||||
// 数据列表
|
||||
dataList: [],
|
||||
@ -240,17 +240,6 @@ export default {
|
||||
// 列表数据查询
|
||||
this.getList()
|
||||
},
|
||||
watch: {
|
||||
'form.storeType': {
|
||||
handler: function(val) {
|
||||
if (val == 1) {
|
||||
this.uploadUrl = '/common/uploadFile'
|
||||
} else if (val == 2) {
|
||||
this.uploadUrl = '/common/UploadFileAliyun'
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
// 查询数据
|
||||
getList() {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user