implemented deleting from server. multiple uploads by uploader handled and displayed on DOM

This commit is contained in:
Abhinav Adduri 2017-05-31 14:08:13 -07:00
parent c25c97fbaa
commit 895c4d364f
5 changed files with 118 additions and 27 deletions

60
app.js
View File

@ -1,9 +1,11 @@
const express = require("express") const express = require("express")
var busboy = require("connect-busboy"); //middleware for form/file upload const busboy = require("connect-busboy");
var path = require("path"); //used for file path const path = require("path");
var fs = require("fs-extra"); //File System - for file manipulation const fs = require("fs-extra");
const bodyParser = require('body-parser');
const app = express() const app = express()
var redis = require("redis"), const redis = require("redis"),
client = redis.createClient(); client = redis.createClient();
client.on("error", function(err) { client.on("error", function(err) {
@ -11,12 +13,9 @@ client.on("error", function(err) {
}) })
app.use(busboy()); app.use(busboy());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "public"))); app.use(express.static(path.join(__dirname, "public")));
app.get("/", function (req, res) {
res.send("Hello World!")
})
app.get("/download/:id", function(req, res) { app.get("/download/:id", function(req, res) {
res.sendFile(path.join(__dirname + "/public/download.html")); res.sendFile(path.join(__dirname + "/public/download.html"));
}); });
@ -25,7 +24,7 @@ app.get("/assets/download/:id", function(req, res) {
let id = req.params.id; let id = req.params.id;
client.hget(id, "filename", function(err, reply) { // maybe some expiration logic too client.hget(id, "filename", function(err, reply) { // maybe some expiration logic too
if (!reply) { if (!reply) {
res.sendStatus(404); res.sendStatus(404);
} else { } else {
res.setHeader("Content-Disposition", "attachment; filename=" + reply); res.setHeader("Content-Disposition", "attachment; filename=" + reply);
@ -42,8 +41,26 @@ app.get("/assets/download/:id", function(req, res) {
}); });
app.route("/upload/:id") app.post("/delete/:id", function(req, res) {
.post(function (req, res, next) { let id = req.params.id;
let delete_token = req.body.delete_token;
if (!delete_token){
res.sendStatus(404);
}
client.hget(id, "delete", function(err, reply) {
if (!reply) {
res.sendStatus(404);
} else {
client.del(id);
fs.unlinkSync(__dirname + "/static/" + id);
res.sendStatus(200);
}
})
});
app.post("/upload/:id", function (req, res, next) {
var fstream; var fstream;
req.pipe(req.busboy); req.pipe(req.busboy);
@ -55,17 +72,26 @@ app.route("/upload/:id")
file.pipe(fstream); file.pipe(fstream);
fstream.on("close", function () { fstream.on("close", function () {
let id = req.params.id; let id = req.params.id;
client.hset(id, "filename", filename, redis.print); let uuid = Math.floor(Math.random() * 10000000).toString()
client.hset(id, "expiration", 0, redis.print); + Math.floor(Math.random() * 10000000).toString()
+ Math.floor(Math.random() * 10000000).toString();
client.hset(id, "filename", filename);
client.hset(id, "expiration", 0);
client.hset(id, "delete", uuid);
// delete the file off the server in 24 hours
setTimeout(function() {
fs.unlinkSync(__dirname + "/static/" + id);
}, 86400000);
client.expire(id, 86400000); client.expire(id, 86400000);
console.log("Upload Finished of " + filename); console.log("Upload Finished of " + filename);
res.send(id); res.send(uuid);
}); });
}); });
}); });
app.listen(3000, function () { app.listen(3000, function () {
console.log("Portal app listening on port 3000!") console.log("Portal app listening on port 3000!")
}) })

View File

@ -9,6 +9,7 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"body-parser": "^1.17.2",
"connect-busboy": "0.0.2", "connect-busboy": "0.0.2",
"express": "^4.15.3", "express": "^4.15.3",
"fs-extra": "^3.0.1", "fs-extra": "^3.0.1",

View File

@ -50,7 +50,7 @@ function download() {
a.click(); a.click();
}) })
.catch(function(err){ .catch(function(err){
alert("This link is either invalid or has expired."); alert("This link is either invalid or has expired, or the uploader has deleted the file.");
console.error(err); console.error(err);
}); });
}) })
@ -60,7 +60,7 @@ function download() {
}; };
fileReader.readAsArrayBuffer(blob); fileReader.readAsArrayBuffer(blob);
} else { } else {
alert("Unable to download excel.") alert("This link is either invalid or has expired, or the uploader has deleted the file.")
} }
}; };
xhr.send(); xhr.send();

View File

@ -12,6 +12,9 @@
</form> </form>
<p id="downloadProgress"></p> <p id="downloadProgress"></p>
<ul id="uploaded_files">
</ul>
</body> </body>
</html> </html>

View File

@ -31,12 +31,40 @@ function onChange(event) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
var hex = ivToStr(random_iv); var hex = ivToStr(random_iv);
xhr.open("post", "/upload/" + hex, true); xhr.open("post", "/upload/" + hex, true);
xhr.addEventListener("progress", updateProgress);
xhr.upload.addEventListener("progress", updateProgress); var li = document.createElement("li");
var name = document.createElement("p");
name.innerHTML = file.name;
li.appendChild(name);
var link = document.createElement("a");
li.appendChild(link);
var progress = document.createElement("p");
li.appendChild(progress);
document.getElementById("uploaded_files").appendChild(li);
xhr.upload.addEventListener("progress", returnBindedLI(progress, name, link, li));
xhr.onreadystatechange = function() { xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) { if (xhr.readyState == XMLHttpRequest.DONE) {
window.crypto.subtle.exportKey("jwk", key).then(function(keydata) { window.crypto.subtle.exportKey("jwk", key).then(function(keydata) {
var curr_name = localStorage.getItem(file.name);
localStorage.setItem(hex, xhr.responseText);
link.innerHTML = "http://localhost:3000/download/" + hex + "/#" + keydata.k;
link.setAttribute("href", "http://localhost:3000/download/" + hex + "/#" + keydata.k);
// if (curr_name) {
// localStorage.setItem(file.name, curr_name + "," + hex);
// } else {
// localStorage.setItem(file.name, hex)
// }
console.log("Share this link with a friend: http://localhost:3000/download/" + hex + "/#" + keydata.k); console.log("Share this link with a friend: http://localhost:3000/download/" + hex + "/#" + keydata.k);
alert("Share this link with a friend: http://localhost:3000/download/" + hex + "/#" + keydata.k); alert("Share this link with a friend: http://localhost:3000/download/" + hex + "/#" + keydata.k);
}) })
@ -80,9 +108,42 @@ function strToIv(str) {
return iv; return iv;
} }
function updateProgress(e) { function returnBindedLI(a_element, name, link, li) {
if (e.lengthComputable) { return function updateProgress(e) {
var percentComplete = Math.floor((e.loaded / e.total) * 100); if (e.lengthComputable) {
document.getElementById("downloadProgress").innerHTML = "Progress: " + percentComplete + "%"; var percentComplete = Math.floor((e.loaded / e.total) * 100);
} a_element.innerHTML = "Progress: " + percentComplete + "%";
}
if (percentComplete === 100) {
var btn = document.createElement("button");
btn.innerHTML = "Delete from server";
btn.addEventListener("click", function() {
var segments = link.innerHTML.split("/");
var key = segments[segments.length - 2];
var xhr = new XMLHttpRequest();
xhr.open("post", "/delete/" + key, true);
xhr.setRequestHeader("Content-Type", "application/json");
if (!localStorage.getItem(key)) return;
xhr.send(JSON.stringify({delete_token: localStorage.getItem(key)}));
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
document.getElementById("uploaded_files").removeChild(li);
}
if (xhr.status === 200) {
console.log("The file was successfully deleted.");
} else {
console.log("The file has expired, or has already been deleted.");
}
}
});
li.appendChild(btn);
}
}
}
}