Upload image using lua - file-upload

I have been trying simple image upload using lua and Openresty web framework. I found many solutions like
lua-resty-upload
lua-resty-post
Using lua-resty-post I got the form data now how do I upload it?
local resty_post = require 'resty.post'
local cjson = require 'cjson'
local post = resty_post:new()
local m = post:read()
ngx.say(cjson.encode(m))
As I'm new to lua I don't understand which one to use.
My requirement is very simple, I need a file attribute and want to upload on some place like in php move_uploaded_file. Is there any simple way to upload a file?

Found the solution. Using lua-resty-post.
upload.html
<form action="/uploadimage" method="post" enctype="multipart/form-data">
<input type="file" name="upload" accept="image/*">
<button>Upload</button>
</form>
nginx.conf
location /uploadimage {
content_by_lua_file image.lua;
}
image.lua
local resty_post = require "resty.post"
local post = resty_post:new({
path = "/my/path", -- path upload file will be saved
name = function(name, field) -- overide name with user defined function
return name.."_"..field
end
})
local m = post:read()

Related

how to print a dynamically generated pdf with printJS

[Note this might be similar to https://stackoverflow.com/questions/48138874/can-make-print-js-print-a-variable, but I don't know PHP]
I have an ASP.Net core action that creates a PDF on the fly. I currently have the PDF download to the client, like so:
<a asp-controller="Home" asp-action="Pdf">Download PDF</a>
and the controller action
public IActionResult Pdf()
{
using (MemoryStream ms = new MemoryStream())
{
...
return File(ms.ToArray(), "application/pdf", "file.pdf");
}
}
Instead, I would like it to go to the print preview dialog of the browser, for which I was planning to use printjs. But I have to specify a server-based file (such as "docs/file.pdf"). The printjs sample is:
<button type="button" onclick="printJS('docs/file.pdf')">Print PDF</button>
Is there a way to cause the printJS file to download the pdf file without needing to save it somewhere?
Doh. Too easy:
<a onclick="printJS('/home/Pdf')">Print PDF</a>
Instead of supplying an href to a file, have the onclick function call printJS with the action name which will execute and download the PDF.

How does the data flow from webserver to webpage.

I am in process of creating a new website. I have done my basic HTML/CSS/JQuery code to generate the webpage. The website is going to display images. Now my questions are around where the images are supposed to be stored and how to retrieve them. I did research but I am all over the place with the architecture.
My understanding is that HTML page will make a query to a web server (like Apache) and get the data/images back and display it? The function of the web server is to provide the data based on the query, is that right? Where is the data like jpeg images, their metadata, link between gallery and images would be stored? Is there another layer of DB somewhere? Would the architecture be HTML<-->Apache<-->DB ?
Or do I just put my images in a database and host the data their. Basically taking out Apache from the architecture? The queries are going to depend only on the current stage in the navigation tree (nothing user specific).
There is no need for DB to use images. It works more this way:
HTML <-> Apache <-> Image
because apache has the ability to deliver files.
Now, there are several differents way of working.
For example, the image can be load dynamically in a php files with images header. In this case, the scheme will be :
HTML <-> Apache <-> PHP <-> Image
To do it, you simply put your images in a folder where apache's user can access.
For example you can have the following structure in /var/www/sitename:
index.html
img / my_image.jpg
And in index.html
<img src="img/my_image.jpg" ... />
Edit to answer you question :
create a php script that will generate the json array, for example :
page.php
<?php
switch($_GET['link']){
case 'link1':
images_links = array(
'path/to/img1',
'path/to/img2',
...
);
break;
case 'link2':
images_links = array(
'path/to/img3',
'path/to/img4',
...
);
break;
}
echo json_encode(images_links);
?>
Let's guess your html is
<a>link1</a>
<a>link2</a>
<img class="imgToChange" src="..."/>
<img class="imgToChange" src="..."/>
...
Then you will add this javascript function to your html
function updateImages(clicked_link){
// get the text of the link
link_text = clicked_link.innerHTML;
// send a request to page.php to get images's urls
$.get( "path/to/page.php?link="+link_text, function( data ) {
// data will be your json array
images_links = data;
// get a table of all images elements that can be changed
var images = document.getElementsByClassName("imgToChange");
// for each image in the json array
for(var k=0; k<images_links.length; k++){
images[k].src = images_links[k];
}
});
}
And you just have to call this function when a link is clicked
<a onclick="updateImages(this)">link1</a>
<a onclick="updateImages(this)">link2</a>
<img class="imgToChange" src="..."/>
<img class="imgToChange" src="..."/>
...

MVC4 C# - How to submit list of object that are being displayed to the user?

I'm working on an MVC4 C# project in VS2010.
I would like to allow the user to upload the contents of a .csv file to a database but there is a requirement to first echo the contents of the file to screen (as a final visual check) before submitting. What would be the best approach of submitting to the database as I am struggling to find a way of persisting the complex object in the view?
Here is the view where I am using a form to allow the user to upload the csv file:
#model IEnumerable<MyNamespace.Models.MyModel>
#{
ViewBag.Title = "Upload";
WebGrid grid = new WebGrid(Model, rowsPerPage: 5);
}
<h2>Upload</h2>
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
<h2>Grid</h2>
#grid.GetHtml(
//Displaying Grid here)
<p>
#Html.ActionLink("Submit", "Insert")
</p>
Here is the action in the controller that processes the csv file:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
//Stream reader will read test.csv file in current folder
StreamReader sr = new StreamReader(path);
//Csv reader reads the stream
CsvReader csvread = new CsvReader(sr);
List<MyModel> listMyModele = new List<MyModel>(); // creating list of model.
csvread.Configuration.RegisterClassMap<MyModelMap>(); // use mapping specified.
listMyModel = csvread.GetRecords<MyModel>().ToList();
sr.Close();
//return View();
return View(listMyModel);
}
Up until this point everything is simple, I can upload the csv to the controller, read using CsvHelper, produce a list of MyModel objects and display in the view within a grid. To reiterate my initial question, is it now possible to submit the complex object (the list of MyModel) from the view as I can't figure out a way of making it available to an action within the controller.
Thank you.
Yes it's possible, It's "easier" if you have a Model with the IEnumerable in it so you can use the naming convention like this:
Property[index].ItemProperty
for every Html input/select field.
If you want to keep the IEnumerable as Model I think the naming convention is something like this:
ItemProperty[index]
So translated in code:
#Html.TextBoxFor(t => t.Property, new { name = "Property[" + i + "]" })
where i comes from a for loop to render all items or something like that.
I have already done it but I can't find the code at the moment. KendoUI uses this scheme for its multirows edit in the grid component.
You can check their POST AJAX requests for the right naming convention.
EDIT 1:
Otherwise you can think about store the model somewhere temporarily and retrieve it every time and updating with user inputs. It's a little more expensive but probably easier to write. Something like an updated csv file or a temporary db table.

I need help in uploading a file to a folder on my server and then adding the file details to a database

I am trying to make a page for my site where users can upload a game, give it a name then the file gets uploaded to a folder on my site and the file name and game name get added to my sql database but it gives an error saying: "System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index" when i try to run it.
My code for this page is:
#{
var db= Database.Open("Games");
var sqlQ = "SELECT * FROM Games";
var data = db.Query(sqlQ);
}
#{
var fileName = "";
if (IsPost) {
var fileSavePath = "";
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
}
var GameName="";
var GameGenre="";
var GameYear="";
if(IsPost){
GameName=Request["formName"];
var SQLINSERT = "INSERT INTO Games (Name, file_path) VALUES (#0, #1)";
db.Execute(SQLINSERT, GameName, fileName);
Response.Redirect("default.cshtml");
}
}
<h1 >Add a new game to the database</h1>
<form action="" method="post">
<p>Name:<input type="text" name="formName" /></p>
#FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag:true,
uploadText:"Add")
The error page says that the problem is with line 11 but i don't know what to change.
As Hightechrider has correctly said, your code should reside in Controllers, not in views. The exception you are getting is because Request.Files is an empty array, so when you're trying to access [0] element, you get an IndexWasOutOfRange error.
I'd recommend you reading the following article for uploading files in ASP.NET MVC. It presents an easier, more consistent and flexible model by putting the code in the controller action. Basically, all code boils down to this:
You create an upload form with submit button and file input.
You create an action that accepts HttpPostedFileBase variable.
You must set the proper enctype to your form if you want to upload files:
<form action="" method="post" enctype="multipart/form-data">

How to upload a file (via web) using Lua?

How do I upload a file, from a browser, using the Lua programming language?
I'm using the Orbit web framework
This sample comes straight from the orbit sample pages/test.op.
<form method="POST" enctype="multipart/form-data" action="test.op">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
$lua{[[
local f = web.input.file
upload = {}
if f then
local name = f.name
local bytes = f.contents
local dest = io.open(web.real_path .. "/" .. name, "wb")
if dest then
dest:write(bytes)
dest:close()
upload[1] = name
end
end
]]}
You can easily adapt this to a normal orbit post handler. You can also take a look at how I used it in my library project, but it's way more complicated than your typical usage I guess.