示例#1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IAttachmentPathProvider attachmentPathProvider)
        {
            loggerFactory.AddFile(Path.Combine(Directory.GetCurrentDirectory(), "log.log"));

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();
            app.ConfigureCustomExceptionMiddleware();

            //app.UseHttpsRedirection();

            var basePath = "/api/attachment";

            app.UseCors(x => x.AllowAnyOrigin());
            app.UseCors(x => x.AllowAnyHeader());

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(attachmentPathProvider.GetPath(), "Files")),
                RequestPath  = new PathString("/Files")
            });


            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            if (env.IsDevelopment())
            {
                app.UseSwagger();
            }
            else
            {
                app.UseSwagger(c => c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
                {
                    swaggerDoc.Servers = new List <OpenApiServer>
                    {
                        new OpenApiServer {
                            Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{basePath}"
                        }
                    };
                }));
            }

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("./v1/swagger.json", "My API V1");
                c.InjectJavascript("https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js");
                c.InjectJavascript("https://unpkg.com/browse/[email protected]/dist/browser-polyfill.min.js", type: "text/html");
                c.InjectJavascript("https://gistcdn.githack.com/Forevka/dede3d7ac835e24518ec38a349140dac/raw/94d095aebdc460d42f90732be5c4ec057ac0a374/customJs.js");
            });
        }
        public async Task <Attachment> SaveAttachment(AttachmentViewModel attachment)
        {
            var  ext         = Path.GetExtension(attachment.UploadFile.FileName);
            var  fileName    = DateTime.UtcNow.ToFileTimeUtc();
            var  havePreview = false;
            Guid hash;

            _httpContext.HttpContext.Request.Headers.TryGetValue("X-Width", out var width);
            _httpContext.HttpContext.Request.Headers.TryGetValue("X-Height", out var height);

            int.TryParse(width, out int widthVal);
            int.TryParse(height, out int heightVal);

            await using (var memoryStream = new MemoryStream())
            {
                await attachment.UploadFile.CopyToAsync(memoryStream);

                using (var hasher = new MD5CryptoServiceProvider())
                    hash = new Guid(hasher.ComputeHash(memoryStream.GetBuffer()));

                var storedAttachment = await _publicContext.Attachment.FirstOrDefaultAsync(s => s.Hash == hash);

                if (storedAttachment != null)
                {
                    return(storedAttachment);
                }

                await using (var fileStream = new FileStream(
                                 Path.Combine(Path.Combine(_attachmentPathProvider.GetPath(), "Files"), fileName + ext),
                                 FileMode.Create))
                {
                    await fileStream.WriteAsync(memoryStream.GetBuffer());
                }
            }

            if (attachment.UploadFile.ContentType.Contains("video"))
            {
                havePreview = true;
                await _previewGeneratorService.GeneratePreviewVideo(Path.Combine(_attachmentPathProvider.GetPath(), "Files"),
                                                                    fileName.ToString(), ext);

                _previewGeneratorService.GeneratePreviewPreload(Path.Combine(_attachmentPathProvider.GetPath(), "Files"), fileName + "_preview", ".png");
            }
            else
            {
                _previewGeneratorService.GeneratePreviewPreload(Path.Combine(_attachmentPathProvider.GetPath(), "Files"), fileName.ToString(), ext);
            }


            var attachmentDb = new Attachment
            {
                ContentType    = attachment.UploadFile.ContentType,
                Path           = "Files/" + fileName + ext,
                Preview        = havePreview ? "Files/" + fileName + "_preview.png" : null,
                Hash           = hash,
                DisplayName    = attachment.UploadFile.FileName,
                PreviewPreload = havePreview ? "Files/" + fileName + "_preview_preload.png"  : "Files/" + fileName + "_preload" + ext,
                Width          = widthVal,
                Height         = heightVal,
            };

            await _publicContext.Attachment.AddAsync(attachmentDb);

            await _publicContext.SaveChangesAsync();

            return(attachmentDb);
        }