这个地方是用的版本是.net 6,elementUI 3,主要是记录上传的后台代码
一:前端elementUI代码
<el-upload v-model:file-list="pagedata.filedata"
class="upload-demo"
action="/FileUpload/UploadLargeFile" <!--请求的地址-->
multiple
:show-file-list="false" <!--不显示文件列表-->
:on-success="c_m_uploadsuccess"> <!--上传文件成功后回调-->
<el-button title="上传" :icon="icon.UploadFilled" circle size="small" />
</el-upload>
回调
function c_m_uploadsuccess(data) {
console.log(data);
//回调,我这个地方是给上传后返回的文件ID赋值到文件列表中。根据自己的实际情况进行回调赋值。
var obj = pagedata.filedata.find(d => d.response&&d.response.msg == data.msg);
obj.id = data.msg;
}
二:后台上传代码
[HttpPost]
[ActionName("UploadLargeFile")]
public async Task<IActionResult> UploadLargeFile()
{
var request = HttpContext.Request;
if (!request.HasFormContentType ||
!MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaTypeHeader) ||
string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value))
{
return new UnsupportedMediaTypeResult();
}
var reader = new MultipartReader(mediaTypeHeader.Boundary.Value, request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition,
out var contentDisposition);
if (contentDisposition == null)
return r_Fail("上传内容错误,请重新上传!");
if (hasContentDispositionHeader && contentDisposition.DispositionType.Equals("form-data") &&
!string.IsNullOrEmpty(contentDisposition.FileName.Value))
{
DateTime CurrentDate = DateTime.Now;
//得到一个uuid
var ID = TJUUID.CreateUUID();
//contentDisposition.FileName.Value 上传文件的名称,通过uuid_文件名称的方式避免文件重复
var fileName = ID + "_" + contentDisposition.FileName.Value;
//得到需要保存的文件路径,我这个地方是通过当前日期进行路径区分的。你们看实际情况
var saveToPath = Path.Combine(getFileSaveUrl(CurrentDate), fileName);
using (var targetStream = System.IO.File.Create(saveToPath))
{
await section.Body.CopyToAsync(targetStream);
}
//把文件的信息存在数据库中
S_File file = new S_File();
file.ID = ID;
file.CreateDate = CurrentDate;
file.FileSize = 0;
file.FileExt = contentDisposition.FileName.Value.Split('.').LastOrDefault();
file.Name = contentDisposition.FileName.Value;
file.FileUrl = $"/{CurrentDate.Year.ToString()}/{CurrentDate.ToString("yyyyMMdd")}/" + fileName;
file.CreateUserID = "";
CommonDAL.Add(file);
//返回文件的id
return r_Success(ID);
}
section = await reader.ReadNextSectionAsync();
}
return r_Fail("上传附件失败!");
}
效果展示:
上传