Esempio n. 1
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string Upload(string dir, ICompatiblePostedFile file)
        {
            var dirPath  = Cms.PhysicPath + dir;
            var fileName = file.GetFileName();
            var filePath = dirPath + file.GetFileName();

            if (File.Exists(filePath))
            {
                return("{\"error\":\"文件已经存在\"}");
            }
            SaveFile(file, filePath);
            return("{\"url\":\"" + dir + fileName + "\"}");
        }
Esempio n. 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string Upload(string dir, ICompatiblePostedFile file)
        {
            var dirPath  = Cms.PhysicPath + dir;
            var fileName = file.GetFileName();

            var filePath = dirPath + file.GetFileName();

            if (File.Exists(filePath))
            {
                return("{\"error\":\"文件已经存在\"}");
            }
            using (var fs = new FileStream(filePath, FileMode.Create))
            {
                file.CopyToAsync(fs);
                fs.Flush();
            }

            return("{\"url\":\"" + dir + fileName + "\"}");
        }
Esempio n. 3
0
        /// <summary>
        /// 获取上传文件的原始名称
        /// </summary>
        /// <returns></returns>
        public static string GetUploadFileRawName(ICompatiblePostedFile file)
        {
            var fileName = file.GetFileName();
            var i        = fileName.LastIndexOf(".", StringComparison.Ordinal);

            if (i == -1)
            {
                return(fileName);
            }
            return(fileName.Substring(0, i));
        }
Esempio n. 4
0
        /// <summary>
        /// 上传
        /// </summary>
        /// <returns>异步则返回进程ID,同步返回上传文件的路径</returns>
        public string Upload(ICompatiblePostedFile postedFile)
        {
            ICompatibleRequest request = HttpHosting.Context.Request;
            String             baseDir = EnvUtil.GetBaseDirectory();

            string[] process   = request.Form("upload_process")[0].Split('|');
            string   processId = process[1];

            if (postedFile == null)
            {
                return(null);
            }

            string fileName = postedFile.GetFileName();
            string fileExt  = fileName.Substring(fileName.LastIndexOf('.') + 1); //扩展名

            InitUplDirectory(baseDir, this._saveAbsoluteDir);
            this._fileInfo = new UploadFileInfo
            {
                Id            = processId,
                ContentLength = postedFile.GetLength(),
                FilePath      = $"{this._saveAbsoluteDir}{this._fileName}.{fileExt}"
            };
            String targetPath = baseDir + this._fileInfo.FilePath;

            if (!this._autoRename && File.Exists(targetPath))
            {
                throw new IOException("文件已存在");
            }
            // 自动将重复的名称命名
            int i = 0;

            while (File.Exists(targetPath))
            {
                i++;
                this._fileInfo.FilePath = $"{this._saveAbsoluteDir}{this._fileName}_{i.ToString()}.{fileExt}";
                targetPath = baseDir + this._fileInfo.FilePath;
            }
            this.SaveStream(postedFile.OpenReadStream(), targetPath);
            return(_fileInfo.FilePath);
        }
Esempio n. 5
0
        /// <summary>
        /// 处理上传
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task UploadRequest(ICompatibleHttpContext context)
        {
            context.Response.ContentType("application/json; charset=utf-8");
            var path = context.Request.GetPath();
            //String aspxUrl = path.Substring(0, path.LastIndexOf("/") + 1);
            String saveUrl = $"{(this._appPath == "/" ? "" : this._appPath)}/{this._rootPath}";

            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();

            extTable.Add("image", "gif,jpg,jpeg,png,bmp,webp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,7z");

            //最大文件大小
            int maxSize = 10240000;

            ICompatiblePostedFile imgFile = context.Request.File("imgFile");

            if (imgFile == null)
            {
                return(this.showError(context, "请选择文件。"));
            }

            String dirPath = EnvUtil.GetBaseDirectory() + this._rootPath;

            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath).Create();
                //return showError(context,"上传目录不存在。");
            }

            String dirName = context.Request.Query("dir");

            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }

            if (!extTable.ContainsKey(dirName))
            {
                return(this.showError(context, "目录名不正确。"));
            }

            String fileName = imgFile.GetFileName();
            String fileExt  = Path.GetExtension(fileName).ToLower();

            if (imgFile.GetLength() > maxSize)
            {
                return(this.showError(context, "上传文件大小超过限制。"));
            }

            if (String.IsNullOrEmpty(fileExt) ||
                Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return(this.showError(context, "上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。"));
            }

            //创建文件夹
            dirPath += dirName + "/";
            saveUrl += dirName + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath).Create();
            }

            String ymd = DateTime.Now.ToString("yyyyMM", DateTimeFormatInfo.InvariantInfo);

            dirPath += ymd + "/";
            saveUrl += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            String originName  = UploadUtils.GetUploadFileName(imgFile);
            String newFileName = originName + fileExt;
            //String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;

            // 自动将重复的名称命名
            String targetPath = dirPath + newFileName;
            int    i          = 0;

            while (File.Exists(targetPath))
            {
                i++;
                newFileName = $"{originName}_{i.ToString()}{fileExt}";
                targetPath  = dirPath + newFileName;
            }

            SaveFile(imgFile, targetPath);

            String fileUrl = saveUrl + newFileName;

            Hashtable hash = new Hashtable();

            hash["error"] = 0;
            hash["url"]   = fileUrl;
            return(context.Response.WriteAsync(JsonAnalyzer.ToJson(hash)));
        }
Esempio n. 6
0
        /// <summary>
        /// 文件上传至远程服务器
        /// </summary>
        /// <param name="url">远程服务地址</param>
        /// <param name="postedFile">上传文件</param>
        /// <param name="parameters">POST参数</param>
        /// <param name="cookieContainer">cookie</param>
        /// <param name="output">远程服务器响应字符串</param>
        public void HttpPostFile(string url, ICompatiblePostedFile postedFile, Dictionary <string, object> parameters,
                                 CookieContainer cookieContainer, ref string output)
        {
            //1>创建请求
            var request = (HttpWebRequest)WebRequest.Create(url);

            //2>Cookie容器
            request.CookieContainer = cookieContainer;
            request.Method          = "POST";
            request.Timeout         = 20000;
            request.Credentials     = CredentialCache.DefaultCredentials;
            request.KeepAlive       = true;

            var boundary      = "----------------------------" + DateTime.Now.Ticks.ToString("x"); //分界线
            var boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            //内容类型
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            //3>表单数据模板
            var formDataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

            //4>读取流
            var buffer = new byte[postedFile.GetLength()];

            postedFile.OpenReadStream().Read(buffer, 0, buffer.Length);

            //5>写入请求流数据
            var strHeader =
                "Content-Disposition:application/x-www-form-urlencoded; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";

            strHeader = string.Format(strHeader, "filedata", postedFile.GetFileName(), postedFile.GetContentType());
            //6>HTTP请求头
            var byteHeader = Encoding.ASCII.GetBytes(strHeader);

            try
            {
                using (var stream = request.GetRequestStream())
                {
                    //写入请求流
                    if (null != parameters)
                    {
                        foreach (var item in parameters)
                        {
                            stream.Write(boundaryBytes, 0, boundaryBytes.Length); //写入分界线
                            var formBytes =
                                Encoding.UTF8.GetBytes(string.Format(formDataTemplate, item.Key, item.Value));
                            stream.Write(formBytes, 0, formBytes.Length);
                        }
                    }

                    //6.0>分界线============================================注意:缺少次步骤,可能导致远程服务器无法获取Request.Files集合
                    stream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    //6.1>请求头
                    stream.Write(byteHeader, 0, byteHeader.Length);
                    //6.2>把文件流写入请求流
                    stream.Write(buffer, 0, buffer.Length);
                    //6.3>写入分隔流
                    var trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                    stream.Write(trailer, 0, trailer.Length);
                    //6.4>关闭流
                    stream.Close();
                }

                var response = (HttpWebResponse)request.GetResponse();
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    output = reader.ReadToEnd();
                }

                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("上传文件时远程服务器发生异常!", ex);
            }
        }