首先上传保存到临时文件夹,上传代码如下
后台添加数据把文件从临时文件夹迁移到正式文件夹中,代码如下
/// <summary>
/// 上传图片 (临时保存)
/// </summary>
/// <returns>成功返回图片URL,失败则返回错误信息</returns>
public AjaxResponse Upload()
{
try
{
var content = Request.Content;
var uploadDir = _appFolders.ImagesFileUpload;
var tempUploadFiles = "/Upload/TempUploadFiles/";
var newFileName = "";
string filePath = "";
var sp = new MultipartMemoryStreamProvider();
Task.Run(async () => await Request.Content.ReadAsMultipartAsync(sp)).Wait();
foreach (var item in sp.Contents)
{
if (item.Headers.ContentDisposition.FileName != null)
{
var filename = item.Headers.ContentDisposition.FileName.Replace("\"", "");
FileInfo file = new FileInfo(filename);
string fileTypes = "gif,jpg,jpeg,png,bmp";
if (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) == -1)
{
throw new ApplicationException("不支持上传文件类型");
}
//if (file.Length> 5242880)
//{
// throw new UserFriendlyException(L("FileUpload_Img_SizeLimit"));
//}
newFileName = "img_" +DateTime.Now.ToString("yyyyMMddhhmmssms") + file.Name ;
string newFilePath = DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/";
filePath =Path.Combine( _appFolders.TempUploadFileFolder, newFileName);
var ms = item.ReadAsStreamAsync().Result;
using (var br = new BinaryReader(ms))
{
if (ms.Length > 1048576 * 5)
{
throw new UserFriendlyException(L("FileUpload_Warn_SizeLimit"));
}
var data = br.ReadBytes((int)ms.Length);
File.WriteAllBytes(filePath, data);
}
}
}
//string pathResul = "{\"errno\": 0,\"data\":[\""+filePath+"\"] }";
return new AjaxResponse(newFileName);
}
catch (UserFriendlyException ex)
{
return new AjaxResponse(new ErrorInfo(ex.Message));
}
}
前端使用layui上传代码如下
//多文件列表示例
layui.use('upload', function () {
var $ = layui.jquery
, upload = layui.upload;
var demoListView = $('#demoList')
, uploadListIns = upload.render({
elem: '#testList'
, url: PublicMethods.apiHttp + '/api/WebFileUpload'
, before: function (obj) { //obj参数包含的信息,跟 choose回调完全一致,可参见上文。
if (HasFile) {
layer.load(); //上传loading
}
else {
}
}
, accept: 'file'
, multiple: true
, auto: false
, bindAction: '#testListAction'
, choose: function (obj) {
files = obj.pushFile(); //将每次选择的文件追加到文件队列
//读取本地文件
obj.preview(function (index, file, result) {
var tr = $(['<tr id="upload-' + index + '">'
, '<td>' + file.name + '</td>'
, '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
, '<td class=\'waitupload\'>等待上传</td>'
, '<td>'
, '<button class="layui-btn layui-btn-mini demo-reload layui-hide">重传</button>'
, '<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">删除</button>'
, '</td>'
, '</tr>'].join(''));
HasFile = true;
//单个重传
tr.find('.demo-reload').on('click', function () {
obj.upload(index, file);
});
//删除
tr.find('.demo-delete').on('click', function () {
delete files[index]; //删除对应的文件
tr.remove();
});
demoListView.append(tr);
});
}
, done: function (res, index,upload) {//, index, upload
//关闭loadings
layer.closeAll('loading');
if (res.success == true) { //上传成功
//返回的类别和名称
var opt = { "fileType": res.result[0].type, "name": res.result[0].name };
arr.push(opt);
var tr = demoListView.find('tr#upload-' + index)
, tds = tr.children();
tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
tds.eq(3).html(''); //清空操作
delete files[index]; //删除文件队列已经上传成功的文件
return;
}
this.error(index, upload);
}
, error: function (index, upload) {
//关闭loadings
layer.closeAll('loading');
var tr = demoListView.find('tr#upload-' + index)
, tds = tr.children();
tds.eq(2).html('<span style="color: #FF5722;" class="errorupload">上传失败</span>');
tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
}
});
})
后台添加数据把文件从临时文件夹迁移到正式文件夹中,代码如下
/// <summary>
/// 新增咨询投诉
/// </summary>
public virtual async Task<ZWDT_ConsultComplainCreateDto> CreateZWDT_ConsultComplainAsync(ZWDT_ConsultComplainCreateDto input)
{
//TODO:新增前的逻辑判断,是否允许新增
if (input.accessoryFiles == null && input.ZWDT_ConsultComplain_Files != null)
{
foreach (var i in input.ZWDT_ConsultComplain_Files)
{
if (!i.Name.IsNullOrWhiteSpace())
{
string tempUploadFile = Path.Combine(_appFolders.TempUploadFileFolder, i.Name);
FileInfo fileInfo = new FileInfo(tempUploadFile);
if (fileInfo.Length > 5242880)
{
throw new UserFriendlyException(L("FileUpload_Img_SizeLimit"));
}
string uploadFileExtension = i.Name.Substring(i.Name.IndexOf('.'), (i.Name.Length - i.Name.IndexOf('.')));
string newFileName = Guid.NewGuid().ToString("N") + uploadFileExtension;
string newFilePath = DateTime.Now.Year.ToString() + "\\" + DateTime.Now.Month.ToString() + "\\" + DateTime.Now.Day.ToString() + "\\";
//将相对路径转换成绝对路径
string path = HttpContext.Current.Server.MapPath(_appFolders.UploadFileFolder);
string uploadFile = Path.Combine(path, newFilePath);
DirectoryHelper.CreateIfNotExists(uploadFile);//创建文件夹
File.Copy(tempUploadFile, uploadFile + newFileName, true);
FileHelper.DeleteIfExists(tempUploadFile);
//获取服务器的域名系统 (DNS) 主机名或 IP 地址和端口号
//var http = await _settingManager.GetSettingValueAsync(AppSettings.General.WebSiteRootAddress);
var strName = i.Name.Substring(0, i.Name.LastIndexOf("."));
i.Name = strName.Substring(strName.IndexOf("_") + 1, strName.Length - strName.IndexOf("_") - 1);
i.Title = i.Name;
i.FilePath = (_appFolders.UploadFileFolder + newFilePath + newFileName).Replace("\\", "/");
}
//附件对应的咨询投诉表中的id
//i.ConsultComplainId = entityId;
//await _zWDT_ConsultComplain_fileRepository.InsertAsync(i);
}
}
var entity = input.MapTo<ZWDT_ConsultComplain>();
if (entity.Mobile.IsNullOrWhiteSpace() && !entity.Phone.IsNullOrWhiteSpace()) {
entity.Mobile = entity.Phone;
}
else if (!entity.Mobile.IsNullOrWhiteSpace() && entity.Phone.IsNullOrWhiteSpace())
{
entity.Phone = entity.Mobile;
}
entity.ReplyState = 0;
entity.Supervisorystate = false;
try
{
var entityId = await _zWDT_ConsultComplainRepository.InsertAndGetIdAsync(entity);
if (input.accessoryFiles != null && input.ZWDT_ConsultComplain_Files == null)
{
ZWDT_ConsultComplain_Files FilesDto;
//图片流上传
List<string> ListImg = ImageUploadMobile(input.accessoryFiles);
foreach (var item in ListImg)
{
FilesDto = new ZWDT_ConsultComplain_Files();
FilesDto.ConsultComplainId = entityId;
FilesDto.Active = 1;
FilesDto.FilePath = item;
FilesDto.FileType = 0;
await _zWDT_ConsultComplain_fileRepository.InsertAsync(FilesDto);
}
}
//流程轨迹
FlowTracksCreateDto dto = new FlowTracksCreateDto();
dto.ConsultId = entityId;//事项id
dto.HandleStatus = 0;//处理状态
await _zWDT_ConsultComplainAppService.CreateFlowWorkTracksAsync(dto);
//推送OA代办事项 (待受理)
//var strBool =await PushAgents(entity.Title, entityId, entity.Type.Value);
}
catch (Exception ex)
{
string s = ex.Message;
_Logger.Info("咨询投诉举报功能-错误:"+s);
throw;
}
return entity.MapTo<ZWDT_ConsultComplainCreateDto>();
}