public IActionResult Dosyaİndir(int id)
        {
            MemoryStream output = new MemoryStream();

            try
            {
                var d = db.Dosya.FirstOrDefault(u => u.ID == id);
                if (d == null)
                {
                    throw new Exception("Hata: Dosya ID'si hatalı");
                }
                string path = Path.Combine(uploadsRoot, d.sysname);

                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                    using (MemoryStream ms = new MemoryStream())
                    {
                        fs.CopyTo(ms);
                        output          = new SIFRELEME().KilitAç(ms);
                        output.Capacity = Convert.ToInt32(d.boyut);
                    }

                string mimeType     = MimeUtility.GetMimeMapping(d.isim + d.uzantı);
                string downloadName = d.isim + d.uzantı;

                return(File(output.GetBuffer(), mimeType, downloadName));
            }
            catch (Exception e)
            {
                return(Json("Hata: " + e.Message));
            }
            finally
            {
                HttpContext.Response.OnCompleted(async() => await Task.Run(() => output.Dispose()));
            }
        }
Exemple #2
0
        public Task <StorageBlobInfo> BlobInfoAsync(string containerName, string fileName)
        {
            if (string.IsNullOrEmpty(containerName))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(containerName));
            }
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(fileName));
            }

            var filePath = FilePath(containerName, fileName);
            var fileInfo = new FileInfo(filePath);

            var ret = new StorageBlobInfo
            {
                Container = new StorageBlobContainerInfo {
                    Name = containerName, Uri = new Uri($"file://{containerName}")
                },
                ContentType = MimeUtility.GetMimeMapping(fileName),
                Filename    = fileName,
                Size        = fileInfo.Length,
                Uri         = new Uri($"file://{containerName}/{fileName}"),
                AbsoluteUri = $"file://{containerName}/{fileName}"
            };

            return(Task.FromResult(ret));
        }
        public async Task <FileDownloadResult> DownloadFile(Uri source, string targetDirectory)
        {
            FileDownloadResult result     = new FileDownloadResult();
            DateTime           startStamp = DateTime.Now;

            try
            {
                if (!String.IsNullOrEmpty(targetDirectory))
                {
                    result.Source          = source;
                    result.Filename        = Path.GetFileName(source.LocalPath);
                    result.TargetDirectory = targetDirectory;
                    result.LocalFilePath   = Path.Combine(result.TargetDirectory, result.Filename);

                    await new WebClient().DownloadFileTaskAsync(source, result.LocalFilePath);

                    if (File.Exists(result.LocalFilePath))
                    {
                        result.Success      = true;
                        result.DownloadTime = DateTime.Now.Subtract(startStamp);
                        result.FileSize     = new FileInfo(result.LocalFilePath).Length;
                        result.MimeType     = MimeUtility.GetMimeMapping(result.LocalFilePath);
                    }
                }
            }
            catch (Exception e)
            {
                result.Success     = false;
                result.ErrorDetail = e;
            }

            return(result);
        }
        private void ProcessGetRequest(HttpListenerContext context)
        {
            if (TryRedirectUrl(context.Response, context.Request.Url.AbsolutePath, out var targetUrl))
            {
                return;
            }

            targetUrl = ResolveUrlRoot(targetUrl);

            if (!ValidateAccess(context.Response, targetUrl))
            {
                return;
            }

            if (File.Exists(targetUrl))
            {
                var mimeType      = MimeUtility.GetMimeMapping(targetUrl);
                var responseBytes = File.ReadAllBytes(targetUrl);

                HttpServer.SetResponseBytes(context.Response, mimeType, responseBytes);
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            }
        }
Exemple #5
0
        ScrapeAsync(ISeed parent, ILookup <string, SeedContent> rootSeeds,
                    ILookup <string, SeedContent> childSeeds,
                    ILookup <string, SeedContent> siblingSeeds)
        {
            using (FileStream romStream = File.OpenRead(parent.Content.Value))
            {
                string inferredMimeType = this.GetMatchingMimetype(romStream);
                if (inferredMimeType != null)
                {
                    return(_("mimetype", inferredMimeType));
                }
            }

            string platformId = rootSeeds["platform"].First().Value;

            if (!this.StoneProvider.Platforms.TryGetValue(platformId, out var platform))
            {
                return(_());
            }

            if (platform.FileTypes.TryGetValue(Path.GetExtension(parent.Content.Value), out string mimeType))
            {
                return(_("mimetype", mimeType));
            }

            return(_("mimetype", MimeUtility.GetMimeMapping(parent.Content.Value)));
        }
        public async Task WriteBlobAsync(string containerName, string fileName, Stream stream, bool overwrite = false)
        {
            if (string.IsNullOrEmpty(containerName))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(containerName));
            }
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(fileName));
            }

            var container = Client.GetContainerReference(containerName);

            var blob = container.GetBlockBlobReference(fileName);

            if (!overwrite && await blob.ExistsAsync())
            {
                throw new IOException($"File exists ({containerName}/{fileName})");
            }

            stream.Position = 0;
            await blob.UploadFromStreamAsync(stream);

            blob.Properties.ContentType = MimeUtility.GetMimeMapping(fileName);
            await blob.SetPropertiesAsync();
        }
Exemple #7
0
        public IEnumerable <UploadResponse> Upload(UploadRequest request)
        {
            var list = new List <UploadResponse>();

            request.Files.ForEach(async file =>
            {
                string contentType = MimeUtility.GetMimeMapping(file.FileName);
                string extension   = Path.GetExtension(file.FileName);

                var content     = ToByteArray(file);
                string subs     = Guid.NewGuid().ToString().Substring(0, 4);
                string fileName = $"{subs}-{request.Ticket}-{file.FileName}";

                var blobClient = new BlobClient(_connectionString, $"{_container}/{request.Ticket}", fileName);

                list.Add(new UploadResponse
                {
                    NomeArquivo = fileName,
                    Url         = blobClient.Uri.AbsoluteUri,
                    ContentType = contentType,
                    Extension   = extension
                });

                using var stream = new MemoryStream(content);
                await blobClient.UploadAsync(stream);
            });

            return(list);
        }
Exemple #8
0
        public void TestUrlWithoutExtensionReturnsUnknownMimeType()
        {
            var    myFile   = "https://test.com/file/random-file";
            string mimeType = MimeUtility.GetMimeMapping(myFile);

            Assert.AreEqual(MimeUtility.UnknownMimeType, mimeType);
        }
        public static string GetMimeType(string file)
        {
            string mimeType = null;
            string suffix   = file.Substring(file.Length - 4);

            if (suffix.Contains("."))
            {
                suffix = suffix.Substring(suffix.LastIndexOf("."));
            }

            // Special rules on non-default supported types
            //if (suffix.Equals(".py"))
            //{
            //    mimeType = "application/x-python-code";
            //}
            // Get file type naturally or set to folder mode
            //else
            //{
            try
            {
                mimeType = MimeUtility.GetMimeMapping(file);
            }
            catch (Exception)
            {
                Console.WriteLine("Error getting Mime-type, asumming it's a folder...");
                mimeType = "application/octet-stream";
            }
            //}
            return(mimeType);
        }
Exemple #10
0
        private static VideoLengthExtractor GetDecoder(string path = "TestData/small.mp4")
        {
            var mime        = MimeUtility.GetMimeMapping(path);
            var videoStream = File.OpenRead(path);
            var decoder     = new VideoLengthExtractor(videoStream.AsRandomAccessStream(), mime, 0L);

            return(decoder);
        }
 public void TestCommonTypes()
 {
     foreach (var t in _expectedTypes)
     {
         var foundType = MimeUtility.GetMimeMapping(t.Key);
         Assert.AreEqual(t.Value, foundType, "Mime string mismatch");
     }
 }
Exemple #12
0
        public async Task <T> UploadFile <T>(string url, byte[] bytes, string fileName)
        {
            if (!_tokenRes.IsValid())
            {
                await ImplicitAuthenticate();
            }

            if (!string.IsNullOrEmpty(_proxyUrl))
            {
                url = _proxyUrl + "?" + url;
            }

            var multiPartContent = new MultipartFormDataContent("----WebKitFormBoundary" + Guid.NewGuid());
            var fileContents     = new ByteArrayContent(bytes);

            fileContents.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                FileName = fileName,
                Name     = "attachment"
            };

            fileContents.Headers.ContentType = new MediaTypeHeaderValue(MimeUtility.GetMimeMapping(fileName));
            multiPartContent.Add(fileContents);

            var gdbVersionContent = new StringContent("", Encoding.UTF8);

            gdbVersionContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "gdbVersion"
            };
            multiPartContent.Add(gdbVersionContent);

            var formatContent = new StringContent("json", Encoding.UTF8);

            formatContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "f"
            };
            multiPartContent.Add(formatContent);

            if (_tokenRes != null)
            {
                var tokenContent = new StringContent(_tokenRes.token, Encoding.UTF8);
                tokenContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = "token"
                };
                multiPartContent.Add(tokenContent);
            }

            var response = await _httpClient.PostAsync(url, multiPartContent);

            var content = await response.Content.ReadAsStringAsync();

            var result = content.FromJson <T>();

            return(result);
        }
Exemple #13
0
        protected string GetContentType(string fileName)
        {
            if (!fileName.EndsWith(@"/"))
            {
                return(MimeUtility.GetMimeMapping(fileName));
            }

            return(MimeUtility.UnknownMimeType);
        }
Exemple #14
0
 public void TestCommonTypesWithOnlyFileNames()
 {
     foreach (var t in _expectedTypes)
     {
         var fileName  = "examplefile." + t.Key;
         var foundType = MimeUtility.GetMimeMapping(fileName);
         Assert.AreEqual(t.Value, foundType, "Mime string mismatch");
     }
 }
Exemple #15
0
 public void TestCommonTypesAsFilePaths()
 {
     foreach (var t in _expectedTypes)
     {
         var filePath  = Path.Combine(Path.GetTempPath(), "examplefile." + t.Key);
         var foundType = MimeUtility.GetMimeMapping(filePath);
         Assert.AreEqual(t.Value, foundType, "Mime string mismatch");
     }
 }
        public async Task SaveAsync(string path, byte[] content)
        {
            var blobContainerClient = await GetBlobClientAsync(settings.ContainerName, true);

            var blobClient = blobContainerClient.GetBlobClient(path);

            using var stream = new MemoryStream(content);
            await blobClient.UploadAsync(stream, new BlobHttpHeaders { ContentType = MimeUtility.GetMimeMapping(path) });
        }
Exemple #17
0
        private HttpResponseMessage GetFile(string path)
        {
            var result     = new HttpResponseMessage(HttpStatusCode.OK);
            var mappedPath = Path.Combine(config.GetContentFolder(), path);
            var stream     = new FileStream(mappedPath, FileMode.Open, FileAccess.Read, FileShare.Read);

            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeUtility.GetMimeMapping(mappedPath));

            return(result);
        }
Exemple #18
0
        public void AddAttachment(string filePath)
        {
            var attachment = new MailAttachment
            {
                FileName    = Path.GetFileName(filePath),
                ContentType = MimeUtility.GetMimeMapping(filePath),
                Data        = File.ReadAllBytes(filePath)
            };

            Attachments.Add(attachment);
        }
Exemple #19
0
 public void TestNullFileArgumentThrowsException()
 {
     try
     {
         MimeUtility.GetMimeMapping(null);
     }
     catch (Exception ex)
     {
         Assert.IsInstanceOfType(ex, typeof(ArgumentNullException));
     }
 }
Exemple #20
0
        private string EmbedImages(string source, out List <LinkedResource> embeddedImages)
        {
            embeddedImages = new List <LinkedResource>();
            var doc = new HtmlDocument();

            doc.LoadHtml(source);

            var images = doc.DocumentNode.SelectNodes("//img");

            if (images != null)
            {
                foreach (var img in images)
                {
                    try
                    {
                        var srcAttr = img.Attributes.FirstOrDefault(a => a.Name.ToLower() == "src");
                        if (srcAttr != null)
                        {
                            if (srcAttr.Value.ToLower().StartsWith("data:"))
                            {
                                // data:image/png;base64,
                                var p1 = srcAttr.Value.Split(',');

                                var lr = new LinkedResource(
                                    new MemoryStream(
                                        Convert.FromBase64String(p1[1])),
                                    p1[0].Split(';')[0].Split(':')[1]
                                    );
                                embeddedImages.Add(lr);
                                img.SetAttributeValue("src", $"cid:{lr.ContentId}");
                            }
                            else
                            {
                                var imgFullPath = Path.Combine(_emailTemplateConfiguration.TemplateFolder, srcAttr.Value);
                                if (File.Exists(imgFullPath))
                                {
                                    var mime = MimeUtility.GetMimeMapping(imgFullPath);
                                    var lr   = new LinkedResource(imgFullPath, mime);
                                    embeddedImages.Add(lr);
                                    img.SetAttributeValue("src", $"cid:{lr.ContentId}");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"Error embending image {img.Name}");
                    }
                }
            }

            return(doc.DocumentNode.OuterHtml);
        }
        private bool ValidateAccess(HttpListenerResponse response, string url)
        {
            if (!IsSubPath(RootPath, url))
            {
                var mimeType = MimeUtility.GetMimeMapping(url);

                response.StatusCode = (int)HttpStatusCode.Forbidden;
                HttpServer.SetResponseText(response, mimeType, "Access denied.");
                return(false);
            }

            return(true);
        }
        public async Task <string> FindVideoFile(Video video)
        {
            await foreach (var file in GetFiles(video))
            {
                string mime = MimeUtility.GetMimeMapping(file);
                if (mime.StartsWith("video"))
                {
                    return(file);
                }
            }

            return(null);
        }
Exemple #23
0
        public async Task <FileStreamResult> FetchImage(int id)
        {
            var f = await _files.GetFile(id);

            if (!_validPictures.Contains(f.Name.Split(".").Last()) || f.Size == 0)
            {
                return(null);
            }
            var mime   = MimeUtility.GetMimeMapping(f.Name);
            var stream = await _files.GetFileContent(id);

            return(new FileStreamResult(stream, mime));
        }
Exemple #24
0
        public static async Task <string> LoadBase64Async(EPath type, string name)
        {
            var pathFile = Path.Combine(VehicleStartup.PathFiles, type.ToDescriptionString(), name);

            if (!File.Exists(pathFile))
            {
                return(null);
            }
            var bytes = await File.ReadAllBytesAsync(pathFile);

            var base64 = Convert.ToBase64String(bytes);

            return($"data:{MimeUtility.GetMimeMapping(name)};base64,{base64}");
        }
        public List <FB_File> get_files_from_paths(Dictionary <string, Stream> file_paths)
        {
            var files = new List <FB_File>();

            foreach (var file_path in file_paths)
            {
                var file = new FB_File();
                file.data     = file_path.Value;
                file.path     = Path.GetFileName(file_path.Key);
                file.mimetype = MimeUtility.GetMimeMapping(file.path);
                files.Add(file);
            }
            return(files);
        }
Exemple #26
0
        public async Task <Guid> CreateFileAsync(CreateMediaItemServiceModel serviceModel)
        {
            var checksum = this.checksumService.GetMd5(serviceModel.File);

            var existingMediaItemVersion = context.MediaItemVersions.FirstOrDefault(x => x.Checksum == checksum && x.Filename == Path.GetFileNameWithoutExtension(serviceModel.File.FileName) && x.IsActive);

            if (existingMediaItemVersion != null)
            {
                return(existingMediaItemVersion.MediaItemId);
            }

            var mediaItem = new MediaItem
            {
                OrganisationId = serviceModel.OrganisationId,
                IsProtected    = false
            };

            context.MediaItems.Add(mediaItem.FillCommonProperties());

            var mediaItemVersion = new MediaItemVersion
            {
                MediaItemId = mediaItem.Id,
                Filename    = Path.GetFileNameWithoutExtension(serviceModel.File.FileName),
                Extension   = Path.GetExtension(serviceModel.File.FileName),
                Folder      = serviceModel.OrganisationId.ToString(),
                MimeType    = MimeUtility.GetMimeMapping(Path.GetExtension(serviceModel.File.FileName)),
                Size        = serviceModel.File.Length,
                Checksum    = checksum,
                CreatedBy   = serviceModel.Username,
                Version     = 1
            };

            context.MediaItemVersions.Add(mediaItemVersion.FillCommonProperties());

            var mediaItemTranslation = new MediaItemTranslation
            {
                MediaItemVersionId = mediaItemVersion.Id,
                Language           = serviceModel.Language,
                Name = Path.GetFileNameWithoutExtension(serviceModel.File.FileName)
            };

            context.MediaItemTranslations.Add(mediaItemTranslation.FillCommonProperties());

            context.SaveChanges();

            await this.mediaRepository.CreateFileAsync(mediaItemVersion.Id, serviceModel.OrganisationId.ToString(), serviceModel.File, serviceModel.File.FileName);

            return(mediaItem.Id);
        }
        internal void ProcessFile(string inputFilePath, string sourceDirectory)
        {
            string resultPath  = inputFilePath;
            string directory   = Path.GetDirectoryName(inputFilePath);
            string extension   = Path.GetExtension(inputFilePath);
            string contentType = MimeUtility.GetMimeMapping(inputFilePath);
            string filenameWithoutExtension = Path.GetFileNameWithoutExtension(inputFilePath);

            // migrate just in main source directory
            if (Path.GetDirectoryName(inputFilePath) == sourceDirectory)
            {
                resultPath = RunMigrateFile(inputFilePath, directory, extension, contentType, filenameWithoutExtension);
            }

            RunZipFile(resultPath, extension, contentType, filenameWithoutExtension, sourceDirectory);
        }
        public async Task <ActionResult <IList <FileDetail> > > GetFileDetail(int id)
        {
            var fileDetail = await _context.FileDetails.FindAsync(id);

            var path = _context.ShaPathDetails.Where(item => fileDetail.FileSha256 == item.FileSha256).Select(inner => inner.FilePath).FirstOrDefault();


            var memory = new MemoryStream();

            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;

            return(File(memory, MimeUtility.GetMimeMapping(fileDetail.FileName), fileDetail.FileName));
        }
    public async Task SaveAsync(string path, Stream stream, bool overwrite = false)
    {
        var blobClient = await GetBlobClientAsync(path, true).ConfigureAwait(false);

        if (!overwrite)
        {
            var blobExists = await blobClient.ExistsAsync().ConfigureAwait(false);

            if (blobExists)
            {
                throw new IOException($"The file {path} already exists.");
            }
        }

        stream.Position = 0;
        await blobClient.UploadAsync(stream, new BlobHttpHeaders { ContentType = MimeUtility.GetMimeMapping(path) }).ConfigureAwait(false);
    }
        public async Task <IActionResult> DownloadSingle(Guid fileId)
        {
            var fileMetadata = _fileMetadataRepository.Get(fileId);

            if (fileMetadata.Store == FileStore.Azure)
            {
                var downloadUrl = await _fileUploadManager.GetAzureFileDownloadLinkAsync(fileMetadata);

                return(RedirectPermanent(downloadUrl));
            }

            var fileStream = await _fileUploadManager.GetFileContentAsync(fileMetadata);

            var contentType = MimeUtility.GetMimeMapping(fileMetadata.FileName);

            return(File(fileStream, contentType, fileMetadata.FileName));
        }