added upload and download command

This commit is contained in:
Stefan Friese 2025-02-04 15:29:05 +00:00
parent dbe33be2c4
commit 9fe1f78c7f
1 changed files with 108 additions and 66 deletions

View File

@ -8,12 +8,13 @@ import (
"html/template"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
"regexp"
"strings"
)
type PageData struct {
@ -299,7 +300,11 @@ func changeDirectory(command string, args []string, currentDir *string) CommandO
}
func fileUploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
if r.Method != http.MethodPost {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "Failed to upload file", http.StatusInternalServerError)
@ -312,7 +317,9 @@ func fileUploadHandler(w http.ResponseWriter, r *http.Request) {
uploadDir = "./"
}
out, err := os.Create(filepath.Join(uploadDir, header.Filename))
os.MkdirAll(uploadDir, os.ModePerm)
destPath := filepath.Join(uploadDir, header.Filename)
out, err := os.Create(destPath)
if err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError)
return
@ -324,16 +331,31 @@ func fileUploadHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Failed to write file", http.StatusInternalServerError)
return
}
cmdOutput := CommandOutput{Command: "upload", Output: "File saved successfully", Error: ""}
// fmt.Fprintf(w, "File %s uploaded successfully to %s", header.Filename, uploadDir)
commandLog = append(commandLog, cmdOutput)
}
w.Write([]byte("File uploaded successfully"))
}
// func fileDownloadHandler(w http.ResponseWriter, r *http.Request) {
// if r.Method == http.MethodPost {
// file, header, err := r.FormFile("file")
func fileDownloadHandler(w http.ResponseWriter, r *http.Request) {
filePath := r.URL.Query().Get("filePath")
if filePath == ""{
http.Error(w, "Filepath is required", http.StatusBadRequest)
return
}
absPath, err := filepath.Abs(filePath)
if err != nil || !fileExists(absPath) {
http.Error(w, "File not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Disposition", "attachement; filename=\""+filepath.Base(absPath)+"\"")
w.Header().Set("Content-Type", "application/octet-stream")
http.ServeFile(w, r, absPath)
}
func fileExists(filePath string) bool {
_, err := os.Stat(filePath)
return !os.IsNotExist(err)
}
func processCommand(command string, currentDir string) CommandOutput {
var errorMsg string
@ -422,6 +444,13 @@ func handler(w http.ResponseWriter, r *http.Request) {
if command == "cd" {
cmdOutput := changeDirectory(command, args, &currentDir)
commandLog = append(commandLog, cmdOutput)
} else if command == "download" {
if len(args) < 1{
http.Error(w, "Usage: download <filePath>", http.StatusBadRequest)
return
}
http.Redirect(w, r, "/download?filePath="+url.QueryEscape(args[0]), http.StatusFound)
return
} else {
cmdOutput := processCommand(input, currentDir)
commandLog = append(commandLog, cmdOutput)
@ -572,39 +601,57 @@ func handler(w http.ResponseWriter, r *http.Request) {
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("command-input").addEventListener("keydown", function(event) {
if (event.key === "Enter") {
let inputVal = this.value.trim();
if (inputVal === "upload") {
document.getElementById("inputFile").click();
const input = document.getElementById("command-input");
const fileInput = document.getElementById("fileInput");
let isUploadTriggered = false;
document.querySelector("form").addEventListener("submit", function(event) {
const command = input.value.trim();
const parts = command.split(" ");
if (parts[0] === "upload") {
event.preventDefault();
if (parts.length === 1) {
fileInput.click();
isUploadTriggered = true;
} else {
const filePath = parts[1];
const targetPath = parts.length > 2 ? parts[2] : ".";
uploadFileFromBrowser(filePath, targetPath);
}
}
});
function requestUpload() {
let fileInput = document.getElementById("inputFile");
console.log("file is");
console.log(fileInput);
fileInput.addEventListener("change", function () {
if (fileInput.files.length > 0 && isUploadTriggered) {
const file = fileInput.files[0];
input.value = 'upload "' + file.name + '"';
isUploadTriggered = false;
}
});
});
function uploadFileFromBrowser(filePath, targetPath) {
const fileInput = document.getElementById("fileInput");
if (fileInput.files.length === 0) {
console.error("No file selected.");
console.error("No file selected");
alert("No file selected");
return;
}
let file = fileInput.files[0];
let formData = new FormData();
const file = fileInput.files[0];
const formData = new FormData();
formData.append("file", file);
fetch("http://localhost:8080/upload", {
fetch("/upload", {
method: "POST",
body: formData
body: formData,
})
.then(response => response.text())
.then(data => {
console.log("Upload succesful:", data);
.then((response) => response.text())
.then((data) => {
console.log("Upload successful:", data);
document.getElementById("command-input").value = "";
})
.catch(error => console.error("Upload failed:", error));
.catch((error) => console.error("Upload failed:", error));
}
});
</script>
<style>
body {
@ -669,13 +716,7 @@ func handler(w http.ResponseWriter, r *http.Request) {
</div>
</form>
</div>
<div>
<form id="fileUpload" action="/upload" method="POST" enctype="multipart/form-data">
<label for="inputFile">Select a file to upload:</label>
<input name="inputFile" id="inputFile" type="file">
<button id="fileUploadButton" onclick="document.getElementById('inputFile').click()">Upload</button>
</form>
</div>
<input type="file" id="fileInput" style="display: none;" onchange="setFilePath()">
</body>
</html>
`))
@ -691,6 +732,7 @@ func handler(w http.ResponseWriter, r *http.Request) {
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/upload", fileUploadHandler)
http.HandleFunc("/download", fileDownloadHandler)
fmt.Println("Starting server on :8080")
http.ListenAndServe(":8080", nil)
}