Skip to content

Instantly share code, notes, and snippets.

@markuman
Created March 9, 2016 08:53
Show Gist options
  • Save markuman/9f280b11d8eb602ae903 to your computer and use it in GitHub Desktop.
Save markuman/9f280b11d8eb602ae903 to your computer and use it in GitHub Desktop.
TurboLua uploading files (post) and garbage collection
#!/usr/bin/luajit
local turbo = require("turbo")
turbo.log.categories.success = true
local df = "test/"
local index = class("index", turbo.web.RequestHandler)
function index:get()
self:write("Hello World!")
end
function index:post()
self:add_header('Content-Type', 'application/json')
local file = self:get_argument("file", "ERROR")
local name = self:get_argument("name", "ERROR")
print("--- RECEIVE UPLOAD ---")
print("filename: " .. name)
local fd1 = io.open(df .. name, "wb")
io.output(fd1)
io.write(file)
io.close(fd1)
file = {}
self:finish()
end
turbo.web.Application({
{"/index/(.*)$", turbo.web.StaticFileHandler, "test/"},
{"/upload", index}
}):listen(8888, "127.0.0.1", {max_body_size=1024*1024*1024})
turbo.ioloop.instance():start()
<html>
<head>
<meta charset="utf-8">
<title>Upload</title>
<script>
function upload(file, name){
var fd = new FormData();
fd.append("file", file);
fd.append("name", name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://127.0.0.1:8888/upload', true);
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
console.log('Server got:', resp);
};
};
xhr.send(fd);
}
function up(file, name){
var fd = new FormData();
fd.append("file", file);
console.log(fd);
}
</script>
</head>
<body>
<div id="login">
<div id="triangle"></div>
<h1>Upload</h1>
<form>
<input type="file" value="file" id="formFileId" name="file"/>
<input value="upload" type="button" id="theButton" onclick="upload(this.form.file.files[0], this.form.file.value)"/>
<input value="test" type="button" id="theButton" onclick="up(this.form.file.files[0], this.form.file.value)"/>
</form>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment