Esempio n. 1
0
        //Checks if the file is a torrent file
        private bool IsTorrentFile(byte[] torrentFileAsBytes)
        {
            //Attempts to guess and return the file type
            string mimeType = MimeGuesser.GuessMimeType(torrentFileAsBytes); //=> image/jpeg

            return(mimeType.Equals(ServiceConstants.TorrentMimeType));
        }
Esempio n. 2
0
        public void GuessMimeFromFilePath()
        {
            string expected = "image/jpeg";
            string actual   = MimeGuesser.GuessMimeType(ResourceUtils.TestDataPath);

            Assert.Equal(expected, actual);
        }
Esempio n. 3
0
        public void GuessMimeFromFilePath()
        {
            var    expected = "image/jpeg";
            string actual   = MimeGuesser.GuessMimeType(ResourceUtils.GetFileFixture);

            Assert.Equal(expected, actual);
        }
Esempio n. 4
0
        public void GuessMimeFromBuffer()
        {
            byte[] buffer   = File.ReadAllBytes(ResourceUtils.GetFileFixture);
            var    expected = "image/jpeg";
            string actual   = MimeGuesser.GuessMimeType(buffer);

            Assert.Equal(expected, actual);
        }
Esempio n. 5
0
        public void GuessMimeFromStream()
        {
            using var stream = File.OpenRead(ResourceUtils.GetFileFixture);
            var    expected = "image/jpeg";
            string actual   = MimeGuesser.GuessMimeType(stream);

            Assert.Equal(expected, actual);
        }
Esempio n. 6
0
        public void GuessMimeFromBuffer()
        {
            byte[] buffer   = File.ReadAllBytes(ResourceUtils.TestDataPath);
            string expected = "image/jpeg";
            string actual   = MimeGuesser.GuessMimeType(buffer);

            Assert.Equal(expected, actual);
        }
Esempio n. 7
0
        // path should be absolute physical address, eg: C:\Repository\
        public static string SaveFile(IFormFile file, FileType fileType, string path)
        {
            if (file.Length <= 0)
            {
                throw new Exception("there is no content in uploaded file.");
            }

            var date         = DateTime.Now;
            var relativePath = $"{fileType}/{date.Year}/{date.Month}/{date.Day}/";
            var folderPath   = Path.Combine(path, relativePath);

            var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);

            Directory.CreateDirectory(folderPath);
            var filepath = Path.Combine(folderPath, fileName);

            using (var fileStream = new FileStream(filepath, FileMode.Create))
            {
                file.CopyTo(fileStream);
            }

            //Check Mime Type
            var allowedExtensions = new List <string>
            {
                "image/png",
                "image/tiff",
                "image/jpeg",
                "image/bmp",
                "image/gif",
            };

            if (fileType == FileType.File)
            {
                allowedExtensions.Add("application/msword");
                allowedExtensions.Add("application/zip");
                allowedExtensions.Add("application/x-rar-compressed");
                allowedExtensions.Add("application/pdf");
                allowedExtensions.Add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                allowedExtensions.Add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            }

            var mimeType = MimeGuesser.GuessMimeType(filepath);

            if (allowedExtensions.Contains(mimeType))
            {
                return(Path.Combine(relativePath, fileName));
            }

            try
            {
                File.Delete(filepath);
            }
            catch (IOException)
            {
            }

            throw new Exception("Invalid File Type");
        }
        public static FileType GetFileType(string filePath)
        {
            var mimeType = MimeGuesser.GuessMimeType(filePath);

            return(mimeType switch {
                "text/plain" => FileType.nTriples,
                "application/x-gzip" => FileType.gZip,
                _ => FileType.Unknown
            });
Esempio n. 9
0
        public AnalyzerResult Analyze(FileItem file)
        {
            var result = new AnalyzerResult();

            result.Properties.Add("mime_type", MimeGuesser.GuessMimeType(file.AbsolutePath));
            result.Properties.Add("mime_extension", MimeGuesser.GuessExtension(file.AbsolutePath));

            return(result);
        }
        public FileResult DownloadCV(string FN)
        {
            string FilePath = ENV.ContentRootPath + "\\wwwroot\\Docs\\CVs\\" + FN;
            string MimeType = MimeGuesser.GuessMimeType(FilePath);

            //MIME Type

            //FileStream FS = new FileStream();
            return(File("/Docs/CVs/" + FN, MimeType, Guid.NewGuid() + Path.GetExtension(FN)));
        }
Esempio n. 11
0
        public void GuessMimeFromStream()
        {
            using (var stream = File.OpenRead(ResourceUtils.TestDataPath))
            {
                string expected = "image/jpeg";
                string actual   = MimeGuesser.GuessMimeType(stream);

                Assert.Equal(expected, actual);
            }
        }
        public FileResult Get(string fileName)
        {
            var path = Path.Combine(uploadPath, fileName);

            if (!System.IO.File.Exists(path))
            {
                return(File(new byte[0], ""));
            }

            var type = MimeGuesser.GuessMimeType(path);

            return(File(System.IO.File.ReadAllBytes(path), type));
        }
Esempio n. 13
0
 public async void GuessMimeFromHttpStream()
 {
     using (var client = new HttpClient())
     {
         var uri = "https://www.google.ru/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
         using (var stream = await client.GetStreamAsync(uri))
         {
             string expected = "image/png";
             string actual   = MimeGuesser.GuessMimeType(stream);
             Assert.Equal(expected, actual);
         }
     }
 }
Esempio n. 14
0
        public static T Create <T>(byte[] content, string name) where T : File, new()
        {
            var result = new T();

            if (content != null)
            {
                result.Data = Convert.ToBase64String(content);
                result.Type = MimeGuesser.GuessMimeType(name);
                result.Name = name;
            }
            ;
            return(result);
        }
Esempio n. 15
0
        public ImageReference Handle(ImageRequest message)
        {
            var imageRef = ShortCode.TryParse(message.Id, out var c)
                ? Index.GetImage(c)
                : Index.GetImageByName(message.Id);

            imageRef.SetLocation(ImageRoot);
            if (message.DetectContentType)
            {
                imageRef.ContentType = MimeGuesser.GuessMimeType(imageRef.FileLocation);
            }

            return(imageRef);
        }
Esempio n. 16
0
 private string GetMimeType(string filePath)
 {
     return(MimeGuesser.GuessMimeType(filePath));
 }
Esempio n. 17
0
 public string GetMimeType(byte[] content)
 {
     return(MimeGuesser.GuessMimeType(content));
 }
Esempio n. 18
0
        public bool IsImage(byte[] content)
        {
            var mimeType = MimeGuesser.GuessMimeType(content);

            return(mimeType.StartsWith("image"));
        }
Esempio n. 19
0
        public static string GetContentType(string filePath)
        {
            var absolutePath = Path.Combine(Directory.GetCurrentDirectory(), filePath);

            return(MimeGuesser.GuessMimeType(absolutePath));
        }
Esempio n. 20
0
        public JsonResult UploadImageLinks()
        {
            //TODO better response ?
            var responseForEachFile  = new List <ResponseModel <string> >();
            var monitorId            = int.Parse(Request.Form.GetValues("monitorId")[0]);
            var uploadImageLinksData = Request.Form.GetValues("uploadImageLink")[0];
            var uploadImageLinks     = uploadImageLinksData.Split(new string[] { "uploadImageLink=" }, StringSplitOptions.RemoveEmptyEntries);

            var monitor = service.GetMonitorVm(monitorId);

            //use webclient to download files from links
            var wc = new WebClient();

            foreach (var link in uploadImageLinks)
            {
                var monitorUploadPath = Settings.ImagesServerUploadPath + "Monitor\\";
                var response          = new ResponseModel <string>();
                //check if url is valid
                if (Uri.IsWellFormedUriString(link, UriKind.RelativeOrAbsolute))
                {
                    //download
                    var currentFile = wc.DownloadData(link);
                    //validation null or empty
                    if (currentFile != null && currentFile.Length > 0)
                    {
                        //guess type
                        MimeGuesser.MagicFilePath = HttpRuntime.BinDirectory + "\\magic.mgc";
                        var fileType = MimeGuesser.GuessMimeType(currentFile);
                        //validation is image ?
                        if (fileType == "image/jpeg" || fileType == "image/png")
                        {
                            //validation size
                            if (currentFile.Length < (7 * 1024 * 1024))
                            {
                                response.IsSuccess = true;
                                //createfile name
                                var fileName = Guid.NewGuid().ToString() + ".jpg";

                                //for local development it's better to use relative paths,
                                //so we are going to use ..\images\monitor instead of C:\ala\...\...\...\bala\images\monitor
                                //If the path contains C:\******* it means it's rooted, and we use the raw value from the settings.
                                //if it contaisn only "..\images\" it will not be rooted and we need to map the IIS directory to rooted path directory
                                string uploadDir = "";
                                if (Path.IsPathRooted(monitorUploadPath))
                                {
                                    uploadDir = Path.Combine(monitorUploadPath, monitor.BrandName, monitor.Model);
                                }
                                else
                                {
                                    uploadDir = Path.Combine(HttpContext.Server.MapPath("~"), monitorUploadPath, monitor.BrandName, monitor.Model);
                                }

                                Directory.CreateDirectory(uploadDir);
                                var imageUrlPath = $@"/{monitor.BrandName}/{monitor.Model}/{fileName}";
                                var uploadPath   = Path.Combine(uploadDir, fileName);

                                //save to hdd
                                using (Image image = Image.FromStream(new MemoryStream(currentFile)))
                                {
                                    image.Save(uploadPath, ImageFormat.Jpeg);
                                }
                                //save to db
                                service.SaveImageToDb(monitorId, imageUrlPath);
                            }
                            else
                            {
                                response.Errors.Add("Image cannot be larger than 7mb");
                            }
                        }
                        else
                        {
                            response.Errors.Add("You can only upload image files(jpeg/png)");
                        }
                    }
                    else
                    {
                        response.Errors.Add("File is null or empty");
                    }
                }
                else
                {
                    response.Errors.Add("Bad Url");
                }
                responseForEachFile.Add(response);
            }
            return(new JsonResult()
            {
                Data = responseForEachFile
            });
        }
Esempio n. 21
0
        public static string SaveFile(IFormFile file, FileConfig config, DomainModels.SSOT.FileType type, string relativePath)
        {
            if (file.Length <= 0)
            {
                throw new Exception("there is no content in uploaded file.");
            }

            var date = DateTime.Now;
            //var relativePath = $"{type}/{date.Year}/{date.Month}/{date.Day}";
            var folderPath = Path.Combine(relativePath, "UploadFiles");

            var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            var filepath = Path.Combine(folderPath, fileName);

            using (var fileStream = new FileStream(filepath, FileMode.Create))
            {
                file.CopyTo(fileStream);
            }

            //Check Mime Type
            var allowedExtensions = new List <string>
            {
                "image/png",
                "image/tiff",
                "image/jpeg",
                "image/bmp",
                "image/gif",
            };

            if (type == DomainModels.SSOT.FileType.file)
            {
                allowedExtensions.Add("application/msword");
                allowedExtensions.Add("application/zip");
                allowedExtensions.Add("application/x-rar-compressed");
                allowedExtensions.Add("application/pdf");
                allowedExtensions.Add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            }

            var mimeType = MimeGuesser.GuessMimeType(filepath);

            if (allowedExtensions.Contains(mimeType))
            {
                return(fileName);
            }


            try
            {
                File.Delete(filepath);
            }
            catch (IOException)
            {
            }

            throw new Exception("فایل مورد نظر غیر مجاز می‌باشد");
        }
Esempio n. 22
0
        private void backgroundWorkerPopulate_DoWork(object sender, DoWorkEventArgs e)
        {
            addLVI        addListViewItemDelegate = AddListViewItem;
            setDetailText setDetailTextDelegate   = SetDetailText;

            /* Full path */
            var fullPath      = new ListViewItem("Location");
            var fullPathValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.ParentDirectoryPath
            };

            fullPath.SubItems.Add(fullPathValue);
            fullPath.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { fullPath });

            /* Windows extension */
            var windowsExtension      = new ListViewItem("Indicated Extension");
            var windowsExtensionValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.Extension.Name
            };

            windowsExtension.SubItems.Add(windowsExtensionValue);
            windowsExtension.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { windowsExtension });

            /* Detected extension */
            var detectedExtension      = new ListViewItem("Detected Extension");
            var detectedExtensionValue = new ListViewItem.ListViewSubItem
            {
                Text = MimeGuesser.GuessExtension(fileItem.AbsolutePath)
            };

            detectedExtension.SubItems.Add(detectedExtensionValue);
            detectedExtension.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { detectedExtension });

            /* MIME Type */
            var mimeType      = new ListViewItem("Detected MIME Type");
            var mimeTypeValue = new ListViewItem.ListViewSubItem
            {
                Text = MimeGuesser.GuessMimeType(fileItem.AbsolutePath)
            };

            mimeType.SubItems.Add(mimeTypeValue);
            mimeType.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { mimeType });

            /* MIME Details */
            var    builder = new StringBuilder();
            string details = detailMagic.Read(fileItem.AbsolutePath);

            details = details.Replace("- data", string.Empty);

            foreach (var component in details.Split(','))
            {
                if (!component.Equals("- data"))
                {
                    builder.AppendLine(component.Trim());
                }
            }

            BeginInvoke(setDetailTextDelegate, new object[] { builder.ToString() });

            /* Size */
            var size      = new ListViewItem("Size");
            var sizeValue = new ListViewItem.ListViewSubItem
            {
                Text = Utils.GetDynamicFileSize(fileItem.AbsolutePath)
            };

            size.SubItems.Add(sizeValue);
            size.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { size });

            /* Creation date + time */
            var creationDateTime      = new ListViewItem("Creation Date");
            var creationDateTimeValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.CreationTimeAsText
            };

            creationDateTime.SubItems.Add(creationDateTimeValue);
            creationDateTime.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { creationDateTime });

            /* Access date + time */
            var accessDateTime      = new ListViewItem("Last Access Date");
            var accessDateTimeValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.LastAccessTimeAsText
            };

            accessDateTime.SubItems.Add(accessDateTimeValue);
            accessDateTime.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { accessDateTime });

            /* Modify date + time */
            var modifiedDateTime      = new ListViewItem("Last Modification Date");
            var modifiedDateTimeValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.LastWriteTimeAsText
            };

            modifiedDateTime.SubItems.Add(modifiedDateTimeValue);
            modifiedDateTime.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { modifiedDateTime });

            /* Attributes */
            var attributes      = new ListViewItem("Windows Attributes");
            var attributesValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.AttributesAsText
            };

            attributes.SubItems.Add(attributesValue);
            attributes.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { attributes });

            /* Owner */
            var owner      = new ListViewItem("Owner");
            var ownerValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.Owner
            };

            owner.SubItems.Add(ownerValue);
            owner.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { owner });
        }
Esempio n. 23
0
        public static string SaveFile(IFormFile file, FileConfig config, FileType fileType, long?length = null)
        {
            if (file.Length <= 0)
            {
                throw new Exception("there is no content in uploaded file.");
            }

            var date         = DateTime.Now;
            var relativePath = $"{fileType}/{date.Year}/{date.Month}/{date.Day}/";
            var folderPath   = Path.Combine(config.PhysicalAddress, relativePath);

            var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);

            Directory.CreateDirectory(folderPath);
            var filepath = Path.Combine(folderPath, fileName);

            var          stream       = file.OpenReadStream();
            MemoryStream memoryStream = new MemoryStream();

            stream.CopyTo(memoryStream);
            var fileByte = memoryStream.ToArray();
            var newBytes = fileByte;

            if (length.HasValue)
            {
                newBytes = ImageResizer.ResizeImage(fileByte, (int)length.Value);
            }

            System.IO.File.WriteAllBytes(filepath, newBytes);


            //Check Mime Type
            var allowedExtensions = new List <string>
            {
                "image/png",
                "image/tiff",
                "image/jpeg",
                "image/bmp",
                "image/gif",
            };

            if (fileType == FileType.file)
            {
                allowedExtensions.Add("application/msword");
                allowedExtensions.Add("audio/mpeg");
                allowedExtensions.Add("audio/x-wav");
                allowedExtensions.Add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                allowedExtensions.Add("application/vnd.ms-excel");
                allowedExtensions.Add("application/octet-stream");
                allowedExtensions.Add("multipart/x-zip");
                allowedExtensions.Add("application/x-rar");
                allowedExtensions.Add("application/zip");
                allowedExtensions.Add("application/x-rar-compressed");
                allowedExtensions.Add("application/x-zip-compressed");
                allowedExtensions.Add("application/pdf");
                allowedExtensions.Add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            }

            var mimeType = MimeGuesser.GuessMimeType(filepath);

            if (allowedExtensions.Contains(mimeType))
            {
                return(Path.Combine(relativePath, fileName));
            }


            try
            {
                File.Delete(filepath);
            }
            catch (IOException)
            {
            }

            throw new Exception("فایل مورد نظر غیر مجاز می‌باشد");
        }