added upload and download command
This commit is contained in:
parent
dbe33be2c4
commit
9fe1f78c7f
174
gommand.go
174
gommand.go
|
@ -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,41 +300,62 @@ func changeDirectory(command string, args []string, currentDir *string) CommandO
|
|||
}
|
||||
|
||||
func fileUploadHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost {
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to upload file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
uploadDir := r.FormValue("uploadDir")
|
||||
if uploadDir == "" {
|
||||
uploadDir = "./"
|
||||
}
|
||||
|
||||
out, err := os.Create(filepath.Join(uploadDir, header.Filename))
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to save file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
_, err = io.Copy(out, file)
|
||||
if err != nil {
|
||||
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)
|
||||
|
||||
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)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
uploadDir := r.FormValue("uploadDir")
|
||||
if uploadDir == "" {
|
||||
uploadDir = "./"
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
_, err = io.Copy(out, file)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to write file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
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, ¤tDir)
|
||||
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,40 +601,58 @@ 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);
|
||||
if (fileInput.files.length === 0) {
|
||||
console.error("No file selected.");
|
||||
return;
|
||||
fileInput.addEventListener("change", function () {
|
||||
if (fileInput.files.length > 0 && isUploadTriggered) {
|
||||
const file = fileInput.files[0];
|
||||
input.value = 'upload "' + file.name + '"';
|
||||
isUploadTriggered = false;
|
||||
}
|
||||
let file = fileInput.files[0];
|
||||
let formData = new FormData();
|
||||
formData.append("file", file);
|
||||
});
|
||||
});
|
||||
|
||||
fetch("http://localhost:8080/upload", {
|
||||
method: "POST",
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
console.log("Upload succesful:", data);
|
||||
function uploadFileFromBrowser(filePath, targetPath) {
|
||||
const fileInput = document.getElementById("fileInput");
|
||||
if (fileInput.files.length === 0) {
|
||||
console.error("No file selected");
|
||||
alert("No file selected");
|
||||
return;
|
||||
}
|
||||
const file = fileInput.files[0];
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
fetch("/upload", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
})
|
||||
.then((response) => response.text())
|
||||
.then((data) => {
|
||||
console.log("Upload successful:", data);
|
||||
document.getElementById("command-input").value = "";
|
||||
})
|
||||
.catch(error => console.error("Upload failed:", error));
|
||||
}
|
||||
});
|
||||
</script>
|
||||
.catch((error) => console.error("Upload failed:", error));
|
||||
}
|
||||
</script>
|
||||
<style>
|
||||
body {
|
||||
background-color: #222;
|
||||
|
@ -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)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue