Exemple #1
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 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()));
            }
        }
        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
        public async Task <Tuple <Stream, string> > DownAsync(string url, string referer, bool isReferer)
        {
            try
            {
                string fileName = "";
                int    count    = 0;
                while (count <= 3)
                {
                    var client = _clientFactory.CreateClient("gzip");
                    if (referer.IsNotEmpty())
                    {
                        client.DefaultRequestHeaders.Add("referer", referer);
                    }
                    var responseMessage = await client.GetAsync(url);

                    if (responseMessage.StatusCode == HttpStatusCode.OK)
                    {
                        fileName = $"image.{MimeUtility.GetExtensionByMime(responseMessage.Content.Headers.ContentType.MediaType)}";
                        //fileName = Path.GetFileName(url);
                        var stream = await responseMessage.Content.ReadAsStreamAsync();

                        return(new Tuple <Stream, string>(stream, fileName));
                    }
                    count += 1;
                }

                return(null);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "下载文件错误:" + url);
                return(null);
            }
        }
        public static string encodeMimeWord(String value,
                                            string charset,
                                            string scheme,
                                            string lineBreakChars,
                                            int lineLength)

        {
            if (lineLength != 76)
            {
                throw new UnimplementedException("Mime line length option");
            }

            if (!lineBreakChars.equals("\r\n"))
            {
                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < lineBreakChars.length(); i++)
                {
                    char ch = lineBreakChars[i];

                    string hex = Integer.toHexString(ch);

                    sb.append("0x");
                    sb.append(hex);
                }

                throw new UnimplementedException(L.l("Mime line break option: '{0}'", sb));
            }

            return(MimeUtility.encodeWord(value, charset, scheme));
        }
Exemple #7
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)));
        }
        /**
         * Encodes a MIME header.
         *
         * XXX: preferences
         *
         * @param field_name header field name
         * @param field_value header field value
         * @param preferences
         * @return encoded mime header
         */
        public static StringValue encodeMime(Env env,
                                             StringValue name,
                                             StringValue value,
                                             string inCharset,
                                             string outCharset,
                                             string scheme,
                                             string lineBreakChars,
                                             int lineLength)

        {
            Decoder decoder = Decoder.create(inCharset);

            CharSequence nameUnicode = decoder.decode(env, name);

            decoder.reset();
            string valueUnicode = decoder.decode(env, value).ToString();

            StringValue sb = env.createUnicodeBuilder();

            sb.append(UnicodeUtility.encode(env, nameUnicode, outCharset));
            sb.append(':');
            sb.append(' ');

            string word = encodeMimeWord(valueUnicode.ToString(),
                                         outCharset,
                                         scheme,
                                         lineBreakChars,
                                         lineLength);

            sb.append(MimeUtility.fold(sb.length(), word));

            return(sb);
        }
        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 #10
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 #11
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 #13
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 #15
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 #16
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 #17
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");
     }
 }
Exemple #18
0
        protected string GetContentType(string fileName)
        {
            if (!fileName.EndsWith(@"/"))
            {
                return(MimeUtility.GetMimeMapping(fileName));
            }

            return(MimeUtility.UnknownMimeType);
        }
        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 #20
0
 public void TestNullFileArgumentThrowsException()
 {
     try
     {
         MimeUtility.GetMimeMapping(null);
     }
     catch (Exception ex)
     {
         Assert.IsInstanceOfType(ex, typeof(ArgumentNullException));
     }
 }
Exemple #21
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 #22
0
        public void TestMimeTypeLookupToGetExtensions()
        {
            var expected = new[] { KnownMimeTypes.FileExtensions.Json, KnownMimeTypes.FileExtensions.Map, KnownMimeTypes.FileExtensions.Topojson };
            var actual   = MimeUtility.GetExtensions(KnownMimeTypes.Json);

            Assert.IsTrue(actual.All(x => expected.Contains(x)));

            var @null = MimeUtility.GetExtensions("invalid");

            Assert.IsNull(@null);
        }
Exemple #23
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 #24
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);
        }
        /**
         * Returns decoded Mime header/field.
         */
        public static StringValue decodeMime(Env env,
                                             CharSequence word,
                                             string charset)

        {
            string decodedStr = MimeUtility.decodeText(word.ToString());

            StringValue str
                = env.createString(MimeUtility.unfold(decodedStr));

            return(str.toBinaryValue(charset));
        }
        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);
        }
        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);
        }
Exemple #28
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));
        }
        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 #30
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}");
        }