Compare commits

...

6 Commits

Author SHA1 Message Date
sigoden
584d33940a chore: upgrade version 2022-05-31 17:02:55 +08:00
sigoden
fc090b6930 fix: not found dir when allow_upload is false 2022-05-31 16:55:52 +08:00
sigoden
19d7b36462 feat: drag and drop uploads, upload folder
close #3
2022-05-31 16:47:06 +08:00
sigoden
755554d3f2 fix: miss file 500 2022-05-31 16:32:50 +08:00
sigoden
6a097e0496 fix: unzip override existed file in uploadonly mode 2022-05-31 15:20:47 +08:00
sigoden
412d42e338 fix: downloaded zip file has no.zip ext in firefox
close #2
2022-05-31 14:39:07 +08:00
7 changed files with 80 additions and 29 deletions

2
Cargo.lock generated
View File

@@ -296,7 +296,7 @@ dependencies = [
[[package]]
name = "duf"
version = "0.6.0"
version = "0.7.0"
dependencies = [
"async-walkdir",
"async_zip",

View File

@@ -1,6 +1,6 @@
[package]
name = "duf"
version = "0.6.0"
version = "0.7.0"
edition = "2021"
authors = ["sigoden <sigoden@gmail.com>"]
description = "Duf is a simple file server."

View File

@@ -12,10 +12,10 @@ Duf is a simple file server.
- Serve static files
- Download folder as zip file
- Search files
- Upload files
- Upload files and folders
- Delete files
- Basic authentication
- Unzip zip file when upload
- Upload zip file then unzip
- Easy to use with curl
## Install

View File

@@ -159,8 +159,6 @@ body {
}
.uploaders {
display: flex;
flex-wrap: wrap;
padding: 0.5em 0;
}

View File

@@ -15,7 +15,7 @@
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg>
</a>
</div>
<div class="upload-control hidden" title="Upload file">
<div class="upload-control hidden" title="Upload files">
<label for="file">
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z"/></svg>
</label>

View File

@@ -1,33 +1,34 @@
let $tbody, $uploaders;
let uploaderIdx = 0;
let baseDir;
class Uploader {
idx = 0;
idx;
file;
name;
$elem;
constructor(idx, file) {
this.idx = idx;
static globalIdx = 0;
constructor(file, dirs) {
this.name = [...dirs, file.name].join("/");
this.idx = Uploader.globalIdx++;
this.file = file;
}
upload() {
const { file, idx } = this;
let url = getUrl(file.name);
const { file, idx, name } = this;
let url = getUrl(name);
if (file.name == baseDir + ".zip") {
url += "?unzip";
}
$uploaders.insertAdjacentHTML("beforeend", `
<div class="uploader path">
<div><svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M6 5H2V4h4v1zM2 8h7V7H2v1zm0 2h7V9H2v1zm0 2h7v-1H2v1zm10-7.5V14c0 .55-.45 1-1 1H1c-.55 0-1-.45-1-1V2c0-.55.45-1 1-1h7.5L12 4.5zM11 5L8 2H1v12h10V5z"></path></svg></div>
<a href="${url}" id="file${idx}">${file.name} (0%)</a>
<a href="${url}" id="file${idx}">${name} (0%)</a>
</div>`);
this.$elem = document.getElementById(`file${idx}`);
const ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", e => this.progress(e), false);
ajax.addEventListener("readystatechange", () => {
console.log(ajax.readyState, ajax.status)
if(ajax.readyState === 4) {
if (ajax.status == 200) {
this.complete();
@@ -44,15 +45,15 @@ class Uploader {
progress(event) {
const percent = (event.loaded / event.total) * 100;
this.$elem.innerHTML = `${this.file.name} (${percent.toFixed(2)}%)`;
this.$elem.innerHTML = `${this.name} (${percent.toFixed(2)}%)`;
}
complete() {
this.$elem.innerHTML = `${this.file.name}`;
this.$elem.innerHTML = `${this.name}`;
}
fail() {
this.$elem.innerHTML = `<strike>${this.file.name}</strike>`;
this.$elem.innerHTML = `<strike>${this.name}</strike>`;
}
}
@@ -141,6 +142,44 @@ async function deletePath(index) {
}
}
function dropzone() {
["drag", "dragstart", "dragend", "dragover", "dragenter", "dragleave", "drop"].forEach(name => {
document.addEventListener(name, e => {
e.preventDefault();
e.stopPropagation();
});
});
document.addEventListener("drop", e => {
if (!e.dataTransfer.items[0].webkitGetAsEntry) {
const files = e.dataTransfer.files.filter(v => v.size > 0);
for (const file of files) {
new Uploader(file, []).upload();
}
} else {
const entries = [];
const len = e.dataTransfer.items.length;
for (let i = 0; i < len; i++) {
entries.push(e.dataTransfer.items[i].webkitGetAsEntry());
}
addFileEntries(entries, [])
}
});
}
async function addFileEntries(entries, dirs) {
for (const entry of entries) {
if (entry.isFile) {
entry.file(file => {
new Uploader(file, dirs).upload();
});
} else if (entry.isDirectory) {
const dirReader = entry.createReader()
dirReader.readEntries(entries => addFileEntries(entries, [...dirs, entry.name]));
}
}
}
function getUrl(name) {
let url = location.href.split('?')[0];
if (!url.endsWith("/")) url += "/";
@@ -184,21 +223,24 @@ function formatSize(size) {
return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
function ready() {
$tbody = document.querySelector(".main tbody");
$uploaders = document.querySelector(".uploaders");
addBreadcrumb(DATA.breadcrumb);
DATA.paths.forEach((file, index) => addPath(file, index));
if (Array.isArray(DATA.paths)) {
const len = DATA.paths.length;
for (let i = 0; i < len; i++) {
addPath(DATA.paths[i], i);
}
}
if (DATA.allow_upload) {
dropzone();
document.querySelector(".upload-control").classList.remove(["hidden"]);
document.getElementById("file").addEventListener("change", e => {
const files = e.target.files;
for (let file of files) {
uploaderIdx += 1;
const uploader = new Uploader(uploaderIdx, file);
uploader.upload();
new Uploader(file, []).upload();
}
});
}

View File

@@ -10,7 +10,10 @@ use headers::{
AccessControlAllowHeaders, AccessControlAllowOrigin, ContentRange, ContentType, ETag,
HeaderMap, HeaderMapExt, IfModifiedSince, IfNoneMatch, IfRange, LastModified, Range,
};
use hyper::header::{HeaderValue, ACCEPT, CONTENT_TYPE, ORIGIN, RANGE, WWW_AUTHENTICATE};
use hyper::header::{
HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_DISPOSITION, CONTENT_TYPE, ORIGIN, RANGE,
WWW_AUTHENTICATE,
};
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, StatusCode};
use percent_encoding::percent_decode;
@@ -131,14 +134,14 @@ impl InnerService {
self.handle_query_dir(filepath, &query[3..], &mut res)
.await?
}
Method::GET if is_dir => self.handle_ls_dir(filepath, true, &mut res).await?,
Method::GET if is_file => {
self.handle_send_file(filepath, req.headers(), &mut res)
.await?
}
Method::GET if is_miss && path.ends_with('/') => {
Method::GET if allow_upload && is_miss && path.ends_with('/') => {
self.handle_ls_dir(filepath, false, &mut res).await?
}
Method::GET => self.handle_ls_dir(filepath, true, &mut res).await?,
Method::OPTIONS => {
status!(res, StatusCode::NO_CONTENT);
}
@@ -191,8 +194,8 @@ impl InnerService {
io::copy(&mut body_reader, &mut file).await?;
let req_query = req.uri().query().unwrap_or_default();
if req_query == "unzip" {
let query = req.uri().query().unwrap_or_default();
if query == "unzip" {
let root = path.parent().unwrap();
let mut zip = ZipFileReader::new(File::open(&path).await?).await?;
for i in 0..zip.entries().len() {
@@ -202,6 +205,9 @@ impl InnerService {
if entry_name.ends_with('/') {
fs::create_dir_all(entry_path).await?;
} else {
if !self.args.allow_delete && fs::metadata(&entry_path).await.is_ok() {
continue;
}
if let Some(parent) = entry_path.parent() {
if fs::symlink_metadata(parent).await.is_err() {
fs::create_dir_all(&parent).await?;
@@ -271,6 +277,7 @@ impl InnerService {
async fn handle_zip_dir(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
let filename = path.file_name().unwrap().to_str().unwrap();
let path = path.to_owned();
tokio::spawn(async move {
if let Err(e) = dir_zip(&mut writer, &path).await {
@@ -279,6 +286,10 @@ impl InnerService {
});
let stream = ReaderStream::new(reader);
*res.body_mut() = Body::wrap_stream(stream);
res.headers_mut().insert(
CONTENT_DISPOSITION,
HeaderValue::from_str(&format!("attachment; filename=\"{}.zip\"", filename,)).unwrap(),
);
Ok(())
}
@@ -388,7 +399,7 @@ impl InnerService {
let pass = {
match &self.args.auth {
None => true,
Some(auth) => match req.headers().get("Authorization") {
Some(auth) => match req.headers().get(AUTHORIZATION) {
Some(value) => match value.to_str().ok().map(|v| {
let mut it = v.split(' ');
(it.next(), it.next())