Ejemplo n.º 1
0
        public static string UploadFile(string fieldName)
        {
            if (HttpContext.Current.Request.Method != "POST")
            {
                return(null);
            }
            var fileField = new FileField(fieldName);
            var files     = HttpContext.Current.Request.Form.Files.GetFiles(fileField.Name);

            if (files.Count == 0)
            {
                throw new InvalidException("请选择文件!");
            }
            var fileName = files[0].FileName;

            if (IsImage(fileName))
            {
                fileField.Type = FieldType.Image;
            }
            else if (IsVideo(fileName))
            {
                fileField.Type = FieldType.Video;
            }
            else if (IsAudio(fileName))
            {
                fileField.Type = FieldType.Audio;
            }
            else if (IsDoc(fileName))
            {
                fileField.Type = FieldType.DocFile;
            }
            else if (IsZip(fileName))
            {
                fileField.Type = FieldType.ZipFile;
            }
            var list = new List <string>();

            foreach (var file in files)
            {
                list.Add(UploadFile(fileField, file));
            }
            return(string.Join(",", list));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 自动创建目录并还回文件名
        /// </summary>
        /// <param name="fileField"></param>
        /// <param name="sourceFileName"></param>
        /// <returns></returns>
        public static string GetFileName(FileField fileField, string sourceFileName)
        {
            string savePath = fileField.SavePath;

            if (string.IsNullOrEmpty(savePath))
            {
                switch (fileField.Type)
                {
                case FieldType.File:
                    savePath = "/upFiles/files";
                    break;

                case FieldType.Image:
                    savePath = "/upFiles/photo";
                    break;

                case FieldType.Video:
                    savePath = "/upFiles/video";
                    break;

                case FieldType.DocFile:
                    savePath = "/upFiles/doc";
                    break;
                }
                savePath += "/" + DateTime.Now.ToString("yyyyMMdd");
            }
            if (!savePath.EndsWith("/") && !Path.HasExtension(savePath))
            {
                savePath += "/";
            }
            var folder = System.IO.Path.GetDirectoryName(MapPath(savePath));

            CreateDirectory(folder);

            string fileName;
            var    ext = Path.GetExtension(sourceFileName);

            if (savePath.Contains("."))
            {
                if (ext == ".webp")
                {
                    fileName = savePath.Replace(Path.GetExtension(savePath), ext);
                }
                else
                {
                    fileName = savePath;
                }
            }
            else
            {
                if (ext == ".webp")
                {
                    ext = ".jpg";
                }
                fileName = string.Format("{0}{1}{2}", savePath, Path.GetRandomFileName(), ext);
            }
            if (!fileName.StartsWith("/upFiles"))
            {
                throw new InvalidException("无效目录!");
            }
            return(fileName);
        }
Ejemplo n.º 3
0
        public static string UploadFile(FileField fileField, Microsoft.AspNetCore.Http.IFormFile formFile = null, string lang = "CN")
        {
            if (HttpContext.Current.Request.Method != "POST")
            {
                return(null);
            }
            if (formFile == null)
            {
                if (HttpContext.Current.Request.Form.Files.Count == 0)
                {
                    return(null);
                }
                if (!string.IsNullOrEmpty(fileField.Name))
                {
                    formFile = HttpContext.Current.Request.Form.Files[fileField.Name];
                }
                else
                {
                    formFile = HttpContext.Current.Request.Form.Files[0];
                }
            }
            if (formFile.Length == 0)
            {
                return(null);
            }
            if (fileField.MaxLength > 0 && formFile.Length > (fileField.MaxLength * 1024))
            {
                throw new InvalidException(lang == "CN" ? $"{fileField.Text}({formFile.FileName})大小不能超过{GetSize(fileField.MaxLength * 1024)}!"
                    : $"{fileField.Text} ({formFile.FileName}) limit in {GetSize(fileField.MaxLength * 1024)}!");
            }

            #region 检查文件名是否正常
            if (Path.GetInvalidFileNameChars().Any(a => formFile.FileName.Contains(a.ToString())))
            {
                throw new InvalidException(lang == "CN" ? $"无效的文件!" : "Invalid file!");
            }
            #endregion

            #region 检查文件扩展名
            switch (fileField.Type)
            {
            case FieldType.File:
                if (!IsSecurityFile(formFile.FileName))
                {
                    throw new InvalidException(lang == "CN" ? $"附件【{fileField.Text}】不被允许的文件!" : $"Attachments ({fileField.Text}) extensions that are not allowed!");
                }
                break;

            case FieldType.DocFile:
                if (!IsDoc(formFile.FileName))
                {
                    throw new InvalidException(lang == "CN" ? $"附件【{fileField.Text}】必需为文档格式!" : $"Attachments \"{fileField.Text}\" must be in docment format!");
                }
                break;

            case FieldType.Image:
                if (!IsImage(formFile.FileName))
                {
                    throw new InvalidException(lang == "CN" ? $"附件【{fileField.Text}】必需为图片格式!" : $"Attachments \"{fileField.Text}\" must be in image format!");
                }
                break;

            case FieldType.Video:
                if (!IsVideo(formFile.FileName))
                {
                    throw new InvalidException(lang == "CN" ? $"附件【{fileField.Text}】必需为视频格式!" : $"Attachments \"{fileField.Text}\" must be in video format!");
                }
                break;

            case FieldType.Audio:
                if (!IsVideo(formFile.FileName))
                {
                    throw new InvalidException(lang == "CN" ? $"附件【{fileField.Text}】必需为音频格式!" : $"Attachments \"{fileField.Text}\" must be in audio format!");
                }
                break;

            case FieldType.ZipFile:
                if (!IsVideo(formFile.FileName))
                {
                    throw new InvalidException(lang == "CN" ? $"附件【{fileField.Text}】必需为压缩文件!" : $"Attachments \"{fileField.Text}\" must be in zip format!");
                }
                break;
            }
            if (fileField.AllowExtensions != null && fileField.AllowExtensions.Length > 0)
            {
                var ext = Path.GetExtension(formFile.FileName).ToLower();
                if (!fileField.AllowExtensions.Contains(ext))
                {
                    throw new InvalidException(lang == "CN" ? $"附件【{fileField.Text}】的扩展名必需为:{string.Join("、", fileField.AllowExtensions)}格式!"
                        : $"The extension of the attachment \"{fileField.Text}\" must be: {string.Join("、", fileField.AllowExtensions)} format!");
                }
            }
            #endregion

            var fileName = GetFileName(fileField, formFile.FileName);
            var savePath = fileName.Substring(0, fileName.LastIndexOf("/"));
            var filePath = MapPath(fileName);
            formFile.SaveAs(filePath);

            var imageField = fileField as ImageField;
            #region 图片处理
            if (imageField != null)
            {
                #region 生成缩略图
                if (!imageField.ThumbSize.IsEmpty)
                {
                    string path;
                    try
                    {
                        if (!string.IsNullOrEmpty(imageField.ThumbPath))
                        {
                            path = fileField.Data.ThumbPath;
                        }
                        else
                        {
                            path = savePath + "/thumb";
                        }
                    }
                    catch
                    {
                        path = savePath + "/thumb";
                    }
                    var saveFolder = MapPath(path);
                    CreateDirectory(saveFolder);
                    var thumbPath = Path.Combine(saveFolder, Path.GetFileName(filePath));
                    CompressImage(filePath, imageField.ThumbSize, imageField.CompressQuality, thumbPath);
                }
                #endregion

                #region 压缩图片
                if (imageField.Compress)
                {
                    var    fName = Path.GetFileNameWithoutExtension(filePath);
                    string compressSavePath;
                    if (imageField.KeepSourceFile)
                    {
                        compressSavePath = filePath.Replace(fName, $"{fName}-compress");
                        fileName         = fileName.Replace(fName, $"{fName}-compress");
                    }
                    else
                    {
                        compressSavePath = filePath;
                    }
                    CompressImage(filePath, imageField.CompressSize, 80, compressSavePath);
                }
                #endregion
            }
            #endregion

            return(fileName);
        }