Пример #1
0
        public Image CreateImageLocally(IEnumerable<ImageSizes> sizes, IHttpPostedFile postedFile)
        {
            foreach (var invalidChar in Path.GetInvalidFileNameChars())
                postedFile.FileName.Replace(invalidChar.ToString(), "");

            var fileKey = Guid.NewGuid();
            var directoryName = fileKey.ToString().Replace("-", "");
            var fileName = Path.ChangeExtension(Bootstrapper.LocalImageName, "png");

            foreach (var size in sizes)
            {
                using (var imageStream = ImageService.ResizeImage(postedFile.InputStream, size))
                {
                    var directoryPath = Path.Combine(Bootstrapper.LocalImagesPath, directoryName, size.ToString());
                    if (!Directory.Exists(directoryPath))
                        Directory.CreateDirectory(directoryPath);

                    var filePath = Path.Combine(directoryPath, fileName);
                    using (var file = System.IO.File.Create(filePath))
                        file.Write(imageStream.ToArray(), 0, (int)imageStream.Length);
                }
            }

            return new Image
                       {
                           Description = "Image",
                           FileKey = fileKey,
                           Owner = _user,
                           Status = ImageStatus.Approved,
                           Title = postedFile.FileName
                       };
        }
Пример #2
0
        public PVContract CreatePVContract(IHttpPostedFile file, IIdentity user, IUser loggedInUser)
        {
            var tempFile = Path.ChangeExtension(Path.GetTempFileName(), ImageHelper.GetExtensionFromMime(file.ContentType));

            file.SaveAs(tempFile);

            var filename = Path.GetFileName(tempFile);
            var pv       = new PVContract {
                Service = PVService.LocalFile, PVId = filename
            };

            using (var mp3 = TagLib.File.Create(tempFile, file.ContentType, ReadStyle.Average))
            {
                pv.Name   = mp3.Tag.Title;
                pv.Author = user.Name;
                pv.Length = (int)mp3.Properties.Duration.TotalSeconds;
            }

            pv.CreatedBy = loggedInUser.Id;

            if (string.IsNullOrEmpty(pv.Name))
            {
                pv.Name = Path.GetFileNameWithoutExtension(file.FileName);
            }

            return(pv);
        }
Пример #3
0
        public T PostFile <T>(Uri requestUri, IHttpPostedFile file, string resource, string operation)
        {
            var response = _http.Post(BuildRequest(requestUri, file.ContentType), file, this.ClientName, resource, operation);

            ValidateResponse(response);

            return(DeserializeContent <T>(response));
        }
Пример #4
0
        public T PostFile <T>(Uri requestUri, IHttpPostedFile file)
        {
            var response = _http.Post(BuildRequest(requestUri, file.ContentType), file);

            ValidateResponse(response);

            return(DeserializeContent <T>(response));
        }
Пример #5
0
        public async Task <T> PostFileAsync <T>(Uri requestUri, IHttpPostedFile file, string resource, string operation)
        {
            var response = await _http.PostAsync(requestUri, file);

            ValidateResponse(response);

            return(DeserializeContent <T>(response));
        }
Пример #6
0
        private void ReadFileStreamToWebRequest(WebRequest webRequest, IHttpPostedFile fileBase)
        {
            using (var requestStream = webRequest.GetRequestStream())
            {
                fileBase.InputStream.CopyTo(requestStream);

                requestStream.Close();
            }
        }
Пример #7
0
 public static byte[] Byte(this IHttpPostedFile file)
 {
     using (var inputStream = file.InputStream())
     {
         using (var memoryStream = new MemoryStream())
         {
             inputStream.CopyTo(memoryStream);
             return(memoryStream.ToArray());
         }
     }
 }
Пример #8
0
        public static HttpPostedFileVO ToVO(IHttpPostedFile file)
        {
            if (file == null || file.ContentLength == 0)
                return null;

            var vo = new HttpPostedFileVO();
            vo.FileName = file.FileName;
            vo.ContentType = file.ContentType;
            vo.Content = new byte[file.InputStream.Length];
            file.InputStream.Read(vo.Content, 0, vo.Content.Length);
            return vo;
        }
Пример #9
0
        public static HttpPostedFileVO ToVO(IHttpPostedFile file)
        {
            if (file == null || file.ContentLength == 0)
            {
                return(null);
            }

            var vo = new HttpPostedFileVO();

            vo.FileName    = file.FileName;
            vo.ContentType = file.ContentType;
            vo.Content     = new byte[file.InputStream.Length];
            file.InputStream.Read(vo.Content, 0, vo.Content.Length);
            return(vo);
        }
Пример #10
0
        public static string WriteToTemp(this IHttpPostedFile file)
        {
            var guid       = Strings.NewGuid();
            var folderPath = Path.Combine(Path.Combine(Directories.Temp(), guid));

            if (!folderPath.Exists())
            {
                Directory.CreateDirectory(folderPath);
            }
            var filePath = Path.Combine(
                folderPath,
                Path.GetFileName(file.FileName));

            file.SaveAs(filePath);
            return(guid);
        }
Пример #11
0
        public IHttpResponse Post(IHttpRequest request, IHttpPostedFile fileBase)
        {
            var webRequest = (HttpWebRequest)ConfigureRequest(request, "POST");

            ReadFileStreamToWebRequest(webRequest, fileBase);

            IHttpResponse response;

            try
            {
                response = BuildResponse((HttpWebResponse)webRequest.GetResponse());
            }
            catch (WebException ex)
            {
                response = HandleException(ex);
            }

            return(response);
        }
Пример #12
0
        public IHttpResponse Post(IHttpRequest request, IHttpPostedFile fileBase)
        {
            var webRequest = (HttpWebRequest)ConfigureRequest(request, "POST");

            ReadFileStreamToWebRequest(webRequest, fileBase);

            IHttpResponse response;

            try
            {
                response = BuildResponse((HttpWebResponse)webRequest.GetResponse());
            }
            catch (WebException ex)
            {
                response = HandleException(ex);
            }

            return response;
        }
 /// <summary>
 /// 检查上传的文件
 /// </summary>
 /// <param name="attribute">上传属性</param>
 /// <param name="file">文件对象</param>
 public static void Check(this FileUploaderFieldAttribute attribute, IHttpPostedFile file)
 {
     if (file == null)
     {
         return;
     }
     else if (!attribute.Extensions.Contains(
                  Path.GetExtension(file.FileName).Substring(1)))
     {
         // 检查后缀
         throw new Exception(string.Format(
                                 new T("Only {0} files are allowed"),
                                 string.Join(",", attribute.Extensions)));
     }
     else if (file.Length > attribute.MaxContentsLength)
     {
         // 检查大小
         throw new Exception(string.Format(
                                 new T("Please upload file size not greater than {0}"),
                                 FileUtils.GetSizeDisplayName((int)attribute.MaxContentsLength)));
     }
 }
Пример #14
0
        public async Task <IHttpResponse> PostAsync(Uri requestUri, IHttpPostedFile file)
        {
            using (var client = new HttpClient())
            {
                var           content = new StreamContent(file.InputStream);
                IHttpResponse response;
                try
                {
                    var r = await client.PostAsync(requestUri, content);

                    response = await BuildResponseAsync(r);
                }
                catch (HttpRequestException ex)
                {
                    response = HandleException(ex);
                }
                catch (TaskCanceledException)
                {
                    response = HandleTaskCanceledException(client.Timeout);
                }
                return(response);
            }
        }
Пример #15
0
 public static string Extension(this IHttpPostedFile file)
 {
     return(Path.GetExtension(file.FileName));
 }
Пример #16
0
 public new Image CreateImageLocally(IEnumerable<ImageSizes> sizes,  IHttpPostedFile postedFile)
 {
     return base.CreateImageLocally(sizes, postedFile);
 }
Пример #17
0
 public object TestActionF(IHttpPostedFile file)
 {
     return(new { filename = file.FileName });
 }
Пример #18
0
        private void ReadFileStreamToWebRequest(WebRequest webRequest, IHttpPostedFile fileBase)
        {
            using (var requestStream = webRequest.GetRequestStream())
            {
                fileBase.InputStream.CopyTo(requestStream);

                requestStream.Close();
            }
        }
        /// <summary>
        /// Encrypt values into a cookie.
        /// </summary>
        /// <param name="cleartext">The decrypted string (cleartext).</param>
        /// <returns>The encrypted string (ciphertext).</returns>

        /*public void EncryptStateInCookie(IDictionary cleartext)
         * {
         *      StringBuilder sb = new StringBuilder();
         *      IEnumerator i = new ArrayList(cleartext).GetEnumerator();
         * bool first = true;
         *      while (i.MoveNext())
         *      {
         *              try
         *              {
         *                  if (!first)
         *                  {
         *      sb.Append("&");
         *                  } else
         *                  {
         *                      first = false;
         *                  }
         *                  DictionaryEntry entry = (DictionaryEntry) i.Current;
         *                      string name = Esapi.Encoder().EncodeForUrl(entry.Key.ToString());
         *                      string cookieValue = Esapi.Encoder().EncodeForUrl(entry.Value.ToString());
         *                      sb.Append(name + "=" + cookieValue);
         *
         *              }
         *              catch (EncodingException e)
         *              {
         *                      // continue
         *              }
         *      }
         *      // FIXME: AAA - add a check to see if cookie length will exceed 2K limit
         *      string encrypted = Esapi.Encryptor().Encrypt(sb.ToString());
         *      this.SafeAddCookie("state", encrypted, - 1, null, null);
         * }*/


        // FIXME: No progress indicator.
        /// <summary> Uses the .NET HttpFileCollection object. to parse the multipart HTTP request
        /// and extract any files therein.
        /// </summary>
        /// <param name="tempDir">
        /// The temporary directory where the file is written.
        /// </param>
        /// <param name="finalDir">
        /// The final directory where the file will be written.
        /// </param>
        /// <seealso cref="Owasp.Esapi.Interfaces.IHttpUtilities.GetSafeFileUploads(FileInfo, FileInfo)">
        /// </seealso>
        public IList GetSafeFileUploads(FileInfo tempDir, FileInfo finalDir)
        {
            ArrayList newFiles = new ArrayList();

            try
            {
                if (!tempDir.Exists)
                {
                    tempDir.Create();
                }
                if (!finalDir.Exists)
                {
                    finalDir.Create();
                }
                IHttpFileCollection fileCollection = ((Authenticator)Esapi.Authenticator()).CurrentRequest.Files;
                if (fileCollection.AllKeys.Length == 0)
                {
                    throw new ValidationUploadException("Upload failed", "Not a multipart request");
                }

                // No progress meter yet
                foreach (string key in fileCollection.AllKeys)
                {
                    IHttpPostedFile file = fileCollection[key];
                    if (file.FileName != null && !file.FileName.Equals(""))
                    {
                        String[] fparts   = Regex.Split(file.FileName, "[\\/\\\\]");
                        String   filename = fparts[fparts.Length - 1];
                        if (!Esapi.Validator().IsValidFileName("upload", filename, false))
                        {
                            throw new ValidationUploadException("Upload only simple filenames with the following extensions " + Esapi.SecurityConfiguration().AllowedFileExtensions, "Invalid filename for upload");
                        }
                        logger.LogCritical(ILogger_Fields.SECURITY, "File upload requested: " + filename);
                        FileInfo f = new FileInfo(finalDir.ToString() + "\\" + filename);
                        if (f.Exists)
                        {
                            String[] parts     = Regex.Split(filename, "\\./");
                            String   extension = "";
                            if (parts.Length > 1)
                            {
                                extension = parts[parts.Length - 1];
                            }
                            String filenm = filename.Substring(0, filename.Length - extension.Length);

                            // Not sure if this is good enough solution for file overwrites
                            f = new FileInfo(finalDir + "\\" + filenm + Guid.NewGuid() + "." + extension);
                        }
                        file.SaveAs(f.FullName);
                        newFiles.Add(f);
                        logger.LogCritical(ILogger_Fields.SECURITY, "File successfully uploaded: " + f);
                    }
                }
                logger.LogCritical(ILogger_Fields.SECURITY, "File successfully uploaded: ");
                //session.Add("progress", System.Convert.ToString(0));
            }

            catch (Exception ex)
            {
                if (ex is ValidationUploadException)
                {
                    throw (ValidationException)ex;
                }
                throw new ValidationUploadException("Upload failure", "Problem during upload");
            }
            return(newFiles);
        }