Save image in folder and retrieve image url in Ktor Web API - ktor

I uploaded image and store it in specific folder, and it's working, but I want the images back as image_url, there is no way found in Ktor Web API.
Please help me if anyone has a solution.
Thanks.

To solve your problem you can serve static files:
embeddedServer(Netty, port = 9999, host = "localhost") {
routing {
static("folder_name") { // web path
files("folder_name") // folder from where to serve files
}
}
}.start(wait = true)
Also, you can have a specific route to respond with the contents of a specific image:
routing {
get("/folder_name/image.jpg") {
call.respondFile(File("./folder_name/image.jpg"))
}
}

Related

Unable to perform get request in ktor framework

I am new to ktor and trying to create api in it.As I have downloaded project from ktor.io and opened it inside IntelliJ idea community edition then run button is showing disabled and when I am running it on right clicking on application.kt file and clicking on run application option.Its showing:
ktor.application - Responding at http://0.0.0.0:8080
When I am going to this link on webpage it is showing:
The web page at http://0.0.0.0:8080/ might be temporarily down or it may have moved permanently to a new web address.
Even if I have get route defined below is my code:
Application.kt
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
configureRouting()
}.start(wait = true)
}
Routing.kt
fun Application.configureRouting() {
// Starting point for a Ktor app:
routing {
get("/") {
call.respondText("Hello World!")
}
}
}
Someone let me know What is an issue and how can I resolve it.

How to create resource file in ASP.NET Core

I use ASP.NET Core. I want to "embbed" text file into application and use it during seeding DataContext only. I don't want anyone to access this file.
As far as I know, if you don't put this text file into the wwwroot folder and don't use the Directory browsing for the whole application, that means no one could access the root path' file.
If you still don't want to let anyone access it trough the http or https. You could write a custom middleware to check the request path, if this path contains the .txt, you could return the access denied response.
More details, you could refer to below codes:
app.Use(async (context, next) => {
if (context.Request.Path.Value.Contains(".txt"))
{
await context.Response.WriteAsync(
$"Acess Denied");
}
else
{
await next();
}
} );
Result:

Static directory with ktor - not under "mysite.com/static/..."

I read through Serving Static Content and am having a brain-block.
I've got a folder /resources/static. It has static stuff in it. Some of that stuff is index.html, favicon.ico, a css folder, a js folder, etc.
I want it to show up as https://example.org/favicon.ico, https://example.org/ (default to index.html), etc.
All the examples in the Docs are for a site that shows up as https://example.org/static/index.html
I'm not getting the difference between "static", "resource", "resources", "files"
routing {
static("static") {
files("css")
files("js")
file("image.png")
file("random.txt", "image.png")
default("index.html")
}
}
static("static") - this is saying that when a client requests [your_host]/static then use the static handler to deal with the request.
Each of the configured handlers will run in order until the first one matches, so if no files match the request under the css directory then the next will run.
files("css") - this tells the static handler to look in a folder called css locally to serve the static content (i.e. client asks for [your_host]/static/style.css will get [app_directory]/css/style.css
file("image.png") - this tells the static handler to return the local file to serve the static content (i.e. client asks for [your_host]/static/* will get [app_directory]/image.png
default("index.html") - this will serve the local file [app_directory]/index.html for any request [your_host]/static/*
resource, resources and defaultResource do the same thing but for resources built in to your app, rather than on the file system.
This MAY have done it.
static("/") {
resources(resourcePackage = "static")
}
defaultResource(resource = "index.html", resourcePackage = "static")

MVC web site: localhost page can’t be found http error 404

I'm developing a Asp.net MVC Core 2.2 web site in IIS.
The IIS website that hosts my MVC Core project has been created correctly. My project generates correctly a PDF file. Usually, I just use a jquery function to open that PDF file in browser:
$.ajax({
url: '#Url.Action("CreatePDF", "MyApiController", new { area= "MyArea" })',
dataType: 'json',
contentType: "application/json",
type: 'POST',
cache: false,
data: JSON.stringify(Filtro),
success: function (d) {
if (d.success == true) {
var item = d.data;
var pageurl = '#Url.Content("~/")' + 'Temporal/' + item.PDFName;
window.open(pageurl, '_blank');
}
},
However, I just realized that this MVC Core web site doesn't allow to open any PDF or txt or jpg or whatever file in browser and instead output this message:
localhost page can’t be found
http error 404
My question is:
In a MVC Core web site, how should I open a PDF file in browser from Controller
[Route("[action]")]
[HttpPost]
public ActionResult<BE_Reporte> CreatePDF(BE_Reporte c)
{
BL_Reporte b = new BL_Reporte();
try
{
c = b.CreatePDF(c);
return Ok(new
{
data = c,
success = true,
Message = "PDF created OK"
});
}
catch (Exception ex) { throw ex; }
finally
{
b.Dispose(); b = null;
}
}
The generated Url for '#Url.Content("~/")' + 'Temporal/' + item.PDFName; will be something like /Temporal/Test.pdf. For this request url, you need to place the Test.pdf in the place CoreMVC2_2\wwwroot\Temporal\Test.pdf.
If you place the Temporal in other folder except wwwroot, it is recommended to move it to wwwroot, otherwise, you need to configure the Serve files outside of web root.
And for client side, you may need to try code below:
var pageurl = '#Url.Content("~/")' + 'Temporal/' + 'Test.pdf';
console.log(pageurl);
var newWindow = window.open("", '_blank');
newWindow.location = pageurl;
Hey the 404 Error says the server did not find the resource you requested. First try to place a break-point at the beginning of the controller action CreatePDF. Then change your attribute routing to [HttpPost("[action]")] and remove the leading [Route("[action]")] call as it might be causing a routing error.
Also, try and add [FromBody] before your parameter.
...([FromBody] BE_Reporte ...)
Also you can use <iframe> HTML tag to display a pdf file or use <embed>
as noted here: Load Generated PDF Data into IFRAME on ASP.NET MVC

Redirect HTTP to HTTPS in MVC4 Mobile Application

In My MVC4 Mobile application i have registration, login page and remaining pages. i would like to redirect user to HTTPS connection for all sensitive information pages like registration and login pages and HTTP to remailing pages.
I prefer you to use conditional functionality putting the class
public class RequireHttpsConditional : RequireHttpsAttribute
{
protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)
{
var useSslConfig = ConfigurationManager.AppSettings["UseSSL"];
if (useSslConfig != null)
{
if (!string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("The requested resource can only be accessed via SSL.");
}
var request = filterContext.HttpContext.Request;
string url = null;
int sslPort;
if (Int32.TryParse(useSslConfig, out sslPort) && sslPort > 0)
{
url = "https://" + request.Url.Host + request.RawUrl;
if (sslPort != 443)
{
var builder = new UriBuilder(url) { Port = sslPort };
url = builder.Uri.ToString();
}
}
if (sslPort != request.Url.Port)
{
filterContext.Result = new RedirectResult(url);
}
}
}
}
and using this [RequireHttpsConditional] above the action result.
i have got this code somewhere in internet and is working fine for me.
in web.config appsettings use <add key="UseSSL" value="443" />
and in the controller above the action result you need put
[RequireHttpsConditional]
public ActionResult SignIn()
{
}
In IIS where you have your project right click and click "Edit Bindings" then you add a custom type https and port no 443 (you can change it)
Note this will work only in production environment. when executed locally it wont be working.
When you execute it locally you have request.Url.Host which will return you only localhost and missing your port number. so if you use it in MVC you will find error loading page for your pages where you put this code.
So this will work when you have the host assigned instead of using the localhost with a specific port number.
Within the controller actions that you wish to be HTTPS add the following code to the top of the method (of course you can simply add this to its own method and then call it):
if (!HttpContext.Request.IsSecureConnection)
{
var url = new UriBuilder(HttpContext.Request.Url);
url.Scheme = "https";
Response.Redirect(url.Uri.AbsoluteUri);
}
It is recommended though that you keep HTTPS on throughout your site to protect against a MITM attack against the auth cookie.