Exemplo n.º 1
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);
        }
Exemplo n.º 2
0
 private void SaveFile(ICompatiblePostedFile imgFile, string targetPath)
 {
     FileUtil.SaveStream(imgFile.OpenReadStream(), targetPath);
 }
Exemplo n.º 3
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);
            }
        }