public static FileInfoParam GetFileInfo(FileMultipartSection fileMultipartSection) { FileInfoParam fileInfo = new FileInfoParam() { FileName = fileMultipartSection.FileName, // FileName = $"{Guid.NewGuid().ToString("N")}{Path.GetExtension(fileMultipartSection.FileName)}", Size = fileMultipartSection.FileStream.Length, FileExtion = Path.GetExtension(fileMultipartSection.FileName) }; fileInfo.FileType = GetFileType(fileInfo.FileExtion); return(fileInfo); }
/// <summary> /// 图片上传 /// </summary> /// <param name="module">所属模块</param> /// <param name="isZip">是否压缩</param> /// <param name="isZoom">是否生成缩略图</param> /// <param name="files">文件</param> /// <returns></returns> public List <FileInfoParam> Upload(string module, bool isZip, bool isZoom, IFormCollection files, string[] attrIds) { List <FileInfoParam> listFileInfo = new List <FileInfoParam>(); string relativePath = string.Format(@"/upload/{0}/{1}", module, DateTime.Now.ToString("yyyyMMdd")); string path = string.Format("{0}{1}", _hostingEnv.WebRootPath, relativePath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } int i = 0; foreach (var item in files.Files) { FileInfoParam fileInfo = new FileInfoParam() { AttachmentId = attrIds[i], FileName = item.FileName, Size = item.Length, Module = module }; var fileExtion = Path.GetExtension(item.FileName); var fileName = string.Format(@"{0}/{1}{2}", path, fileInfo.AttachmentId, fileExtion); Task.Run(() => { FileStream fs = new FileStream(fileName, FileMode.Create); item.CopyTo(fs); fs.Close(); fs.Dispose(); }).GetAwaiter().GetResult(); var saveFileName = string.Format(@"{0}/{1}{2}", path, fileInfo.AttachmentId, fileExtion); ImageUtil.JpgImgZip(fileName, saveFileName, isZoom); if (File.Exists(fileName)) { File.Delete(fileName); } fileInfo.FileType = fileInfo.FileType = GetFileType(fileExtion); fileInfo.LocalUrl = string.Format(@"{0}/{1}{2}", relativePath, fileInfo.AttachmentId, fileExtion); listFileInfo.Add(fileInfo); i++; } return(listFileInfo); }
/// <summary> /// 全景上传 /// </summary> /// <param name="resourceId"></param> /// <param name="files"></param> /// <returns></returns> public async Task <List <FileInfoParam> > UploadPanoImage(string resourceId, IFormCollection files, string[] attrIds) { List <FileInfoParam> listFileInfo = new List <FileInfoParam>(); string relativePath = string.Format(@"/upload/Pano/{0}/", resourceId); string path = string.Format("{0}{1}", _hostingEnv.WebRootPath, relativePath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } int i = 0; foreach (var item in files.Files) { FileInfoParam fileInfo = new FileInfoParam() { AttachmentId = attrIds[i], FileName = item.FileName, Size = item.Length, Module = resourceId }; var fileExtion = Path.GetExtension(item.FileName); var fileName = string.Format(@"{0}{1}{2}", path, fileInfo.AttachmentId, fileExtion); await Task.Run(() => { FileStream fs = new FileStream(fileName, FileMode.Create); item.CopyTo(fs); fs.Close(); }); var type = fileInfo.FileType = GetFileType(fileExtion); fileInfo.FileType = type; if (type != FileType.Image) { throw new Exception("全景只能上传图片"); } fileInfo.LocalUrl = string.Format(@"{0}{1}{2}", relativePath, fileInfo.AttachmentId, fileExtion); listFileInfo.Add(fileInfo); i++; } return(listFileInfo); }
/// <summary> /// 如果文件上传成功,那么message会返回一个上传文件的路径,如果失败,message代表失败的消息 /// </summary> /// <param name="request"></param> /// <param name="targetDirectory"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static async Task <(bool success, IResultModel result, FormValueProvider valueProvider)> StreamFile(this HttpRequest request, FileUploadOption option, CancellationToken cancellationToken) { //读取boundary var boundary = request.GetMultipartBoundary(); if (string.IsNullOrEmpty(boundary)) { return(false, ResultModel.Failed("解析失败"), null); } //检查相应目录 var childDir = Path.Combine(option.Module, DateTime.Now.ToString("yyyyMM")); var fileDirectory = Path.Combine(option.Root, childDir); if (!Directory.Exists(fileDirectory)) { Directory.CreateDirectory(fileDirectory); } //准备文件保存路径 var fileReqestPath = string.Empty; var physicalFilefilePath = string.Empty; //准备viewmodel缓冲 var accumulator = new KeyValueAccumulator(); //创建section reader var reader = new MultipartReader(boundary, request.Body); FileInfoParam fileInfo = new FileInfoParam(); try { var section = await reader.ReadNextSectionAsync(cancellationToken); while (section != null) { ContentDispositionHeaderValue header = section.GetContentDispositionHeader(); if (header.FileName.HasValue || header.FileNameStar.HasValue) { var fileSection = section.AsFileSection(); //检测上传类型 var originalfileName = header.FileName.HasValue ? header.FileName.Value : ""; if (!originalfileName.CheckExtesionSupportType(option) || !fileSection.FileStream.CheckSupportType(option)) { var errorExtension = ""; if (header.FileName.HasValue) { errorExtension = Path.GetExtension(header.FileName.Value); } return(false, ResultModel.Failed($"文件类型不支持上传:{errorExtension}"), null); } fileInfo = GetFileInfo(fileSection); //var fileName = fileSection.FileName; var fileName = $"{Guid.NewGuid().ToString("N")}{Path.GetExtension(fileSection.FileName)}"; fileReqestPath = Path.Combine(option.RequestPath, childDir, fileName); physicalFilefilePath = Path.Combine(fileDirectory, fileName); if (File.Exists(physicalFilefilePath)) { return(false, ResultModel.Failed("你以上传过同名文件"), null); } accumulator.Append("mimeType", fileSection.Section.ContentType); accumulator.Append("fileName", fileName); accumulator.Append("filePath", fileReqestPath); //using (var writeStream = File.Create(filePath)) using (var writeStream = File.Create(physicalFilefilePath)) { const int bufferSize = 1024; await fileSection.FileStream.CopyToAsync(writeStream, bufferSize, cancellationToken); } } else { var formDataSection = section.AsFormDataSection(); var name = formDataSection.Name; var value = await formDataSection.GetValueAsync(); accumulator.Append(name, value); } section = await reader.ReadNextSectionAsync(cancellationToken); } fileInfo.LocalUrl = fileReqestPath; } catch (OperationCanceledException) { if (File.Exists(physicalFilefilePath)) { File.Delete(physicalFilefilePath); } return(false, ResultModel.Failed("用户取消操作"), null); } // Bind form data to a model var formValueProvider = new FormValueProvider( BindingSource.Form, new FormCollection(accumulator.GetResults()), CultureInfo.CurrentCulture); return(true, ResultModel.Success(fileInfo), formValueProvider); }