Compare commits

..

No commits in common. "c41ff56ffa3f86af02be0772cee90d798c733020" and "49b95701fc65e54402338d15b81720042354ae51" have entirely different histories.

5 changed files with 63 additions and 75 deletions

View File

@ -1,5 +1,5 @@
pkgname=simplefileshare pkgname=simplefileshare
pkgver=0.1.4 pkgver=0.1.3
pkgrel=0 pkgrel=0
pkgdesc="Simple file share" pkgdesc="Simple file share"
arch=('x86_64' 'aarch64') arch=('x86_64' 'aarch64')

View File

@ -74,37 +74,30 @@ func HandleUpload(w http.ResponseWriter, r *http.Request) {
return return
} }
var errors []string file, header, err := r.FormFile("file")
for _, header := range r.MultipartForm.File["file"] {
file, err := header.Open()
if err != nil { if err != nil {
errors = append(errors, err.Error()) http.Error(w, err.Error(), http.StatusBadRequest)
continue return
} }
defer file.Close() defer file.Close()
filePath := filepath.Join(config.StoragePath, header.Filename) filePath := filepath.Join(config.StoragePath, header.Filename)
if _, err := os.Stat(filePath); !os.IsNotExist(err) { if _, err := os.Stat(filePath); !os.IsNotExist(err) {
errors = append(errors, fmt.Sprintf("файл с именем %s уже существует", header.Filename)) http.Error(w, "файл с таким именем уже существует", http.StatusBadRequest)
continue return
} }
f, err := os.Create(filePath) f, err := os.Create(filePath)
if err != nil { if err != nil {
errors = append(errors, err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError)
continue return
} }
defer f.Close() defer f.Close()
_, err = io.Copy(f, file) _, err = io.Copy(f, file)
if err != nil { if err != nil {
errors = append(errors, err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError)
continue return
}
}
if len(errors) > 0 {
http.Error(w, strings.Join(errors, "\n"), http.StatusBadRequest)
} }
} }
@ -134,7 +127,7 @@ func HandleDownload(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Accept-Ranges", "none") w.Header().Set("Accept-Ranges", "none")
w.Header().Set("Content-Length", strconv.Itoa(int(fileStat.Size()))) w.Header().Set("Content-Length", strconv.Itoa(int(fileStat.Size())))
_, _ = io.CopyBuffer(w, f, make([]byte, 4096)) io.CopyBuffer(w, f, make([]byte, 4096))
} }
func HandleStream(w http.ResponseWriter, r *http.Request) { func HandleStream(w http.ResponseWriter, r *http.Request) {
@ -164,5 +157,5 @@ func HandleIcon(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/svg+xml") w.Header().Set("Content-Type", "image/svg+xml")
w.Header().Set("Cache-Control", "public, max-age=31557600") w.Header().Set("Cache-Control", "public, max-age=31557600")
_, _ = io.Copy(w, f) io.Copy(w, f)
} }

View File

@ -28,7 +28,7 @@ func init() {
} }
if config.RemoveFilePeriod > 0 { if config.RemoveFilePeriod > 0 {
go removeOldFilesThread(time.Duration(config.RemoveFilePeriod) * time.Hour) go removeOldFilesThread(config.StoragePath, time.Duration(config.RemoveFilePeriod)*time.Hour)
} }
http.HandleFunc("/", HandleRoot) http.HandleFunc("/", HandleRoot)

View File

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="ru"> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
@ -12,12 +12,12 @@
<body> <body>
<header> <header>
<span> <span>
<img src="/favicon.svg" alt="icon"> <img src="/favicon.svg">
File Storage File Storage
</span> </span>
<label> <label>
<input id="file-uploader" type="file" multiple> <input id="file-uploader" type="file" id="upload-button">
Загрузить файл(ы) Загрузить файл
</label> </label>
</header> </header>
<main> <main>
@ -30,47 +30,42 @@
<th>Размер</th> <th>Размер</th>
<th>Дата</th> <th>Дата</th>
</tr> </tr>
{{range .Files}} <tr> {{range .Files}} <tr>
<td><img src="/icon?ext={{.Ext}}"> <a href="/download?filename={{.Name}}">{{.Name}}</a> <a class="right" href="/stream?filename={{.Name}}">просмотр</a></td> <td><img src="/icon?ext={{.Ext}}"> <a href="/download?filename={{.Name}}">{{.Name}}</a> <a class="right" href="/stream?filename={{.Name}}">просмотр</a></td>
<td> <td><pre>{{.Size}}</pre></td>
<pre>{{.Size}}</pre>
</td>
<td>{{.Date}}</td> <td>{{.Date}}</td>
</tr> </tr>
{{end}} {{end}} </table>
</table>
</main> </main>
<footer> <footer>
Файлы хранятся как минимум {{.StorageDuration}} ч. Файлы хранятся как минимум {{.StorageDuration}} ч.
</footer> </footer>
<script> </body>
function myProgressHandler(event) {
var p = Math.floor(event.loaded / event.total * 100);
document.querySelector("label").innerHTML = 'Загрузка: ' + p + '%...';
}
function myOnLoadHandler(event) { </html>
<script type="text/javascript">
function myProgressHandler(event) {
var p = Math.floor(event.loaded/event.total*100);
document.querySelector("label").innerHTML = 'Загрузка: ' + p + '%...';
}
function myOnLoadHandler(event) {
const response = event.currentTarget; const response = event.currentTarget;
if (response.status != 200) { if (response.status != 200) {
alert('Ошибка при загрузке:\n' + response.responseText); alert('Ошибка при загрузке файла:\n' + response.responseText);
} }
document.querySelector("label").innerHTML = 'Загрузка завершена.'; document.querySelector("label").innerHTML = 'Загрузка завершена.';
window.location.reload(); location.reload();
} }
document.getElementById("file-uploader").addEventListener('change', (e) => { document.getElementById("file-uploader").addEventListener('change', (e) => {
var file = document.getElementById("file-uploader").files[0];
var formData = new FormData; var formData = new FormData;
var ajax = new XMLHttpRequest;
for (var i = 0; i < document.getElementById("file-uploader").files.length; i++) {
file = document.getElementById("file-uploader").files[i];
formData.append('file', file); formData.append('file', file);
} var ajax = new XMLHttpRequest;
ajax.upload.addEventListener("progress", myProgressHandler, false); ajax.upload.addEventListener("progress", myProgressHandler, false);
ajax.addEventListener('load', myOnLoadHandler, false); ajax.addEventListener('load', myOnLoadHandler, false);
ajax.open('POST', '/upload', true); ajax.open('POST', '/upload', true);
ajax.send(formData); ajax.send(formData);
}); });
</script> </script>
</body>
</html>

View File

@ -8,12 +8,12 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
func removeOldFilesThread(olderThan time.Duration) { func removeOldFilesThread(path string, olderThan time.Duration) {
ticker := time.NewTicker(time.Hour) ticker := time.NewTicker(time.Hour)
for range ticker.C { for _ = range ticker.C {
log.Debugln("Removing old files...") log.Debugln("Removing old files...")
err := removeOldFiles(olderThan) err := removeOldFiles(path, olderThan)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
@ -21,7 +21,7 @@ func removeOldFilesThread(olderThan time.Duration) {
} }
} }
func removeOldFiles(olderThan time.Duration) error { func removeOldFiles(path string, olderThan time.Duration) error {
return filepath.Walk(config.StoragePath, func(path string, info os.FileInfo, err error) error { return filepath.Walk(config.StoragePath, func(path string, info os.FileInfo, err error) error {
if err != nil { if err != nil {
return err return err