Skip to content

Commit

Permalink
file blob
Browse files Browse the repository at this point in the history
  • Loading branch information
csznet committed Oct 17, 2023
1 parent 8622051 commit 31eca26
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 26 deletions.
77 changes: 66 additions & 11 deletions assets/templates/files.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,70 @@
<div id="loading">上传中...</div>
<div id="response" class="ui-widget"></div>
<script>
function uploadImg(e) {
function uploadFile(file) {
var limit = 10 * 1024 * 1024;
if (file.size <= limit) {
uploadImg(file,1).then((url) => {
// 处理上传成功的情况
console.log(url);
}).catch((error) => {
// 处理上传失败的情况
console.error(error);
});
} else {
// 文件大于20MB,需要分割成多个块
var chunkSize = limit; // 20MB
var start = 0;
var end = Math.min(chunkSize, file.size);

function uploadNextChunk() {
if (start < file.size) {
var chunk = file.slice(start, end);
return uploadImg(chunk,0)
.then((url) => {
// 处理上传成功的情况
temp = temp+'\n'+ url.replace(/^\/d\//, ''); // 每次改变值都换行
start = end;
end = Math.min(start + chunkSize, file.size);
return uploadNextChunk(); // 上传下一个块
})
.catch((error) => {
// 处理上传失败的情况
console.error(error);
});
} else {
return Promise.resolve(); // 如果所有块都上传完成,返回一个已解决的 Promise
}

}
var temp = "tgstate-blob";
temp = temp+'\n' + file.name;
uploadNextChunk()
.then(() => {
console.log(temp); // 所有块上传完成后打印
// 将字符串转换为 Blob 对象
var blob = new Blob([temp], { type: 'text/plain' });

// 创建一个文件对象
var fileAll = new File([blob], 'fileAll.txt', { type: 'text/plain' });
return uploadImg(fileAll, 1);
})
.catch((error) => {
// 处理上传失败的情况
console.error(error);
});
}
}
function uploadImg(e,ms) {
return new Promise((resolve, reject) => {
var o = new FormData();
o.append("image", e);
// 判断是否为图片

var isImage = e.type.startsWith('image/');
$("#uploadButton").prop("disabled", !0);
$("#uploadButton").text("上传中");
$("#loading").show();
// 判断是否为图片

var a = window.location.protocol + "//" + window.location.hostname;
"80" !== window.location.port &&
0 < window.location.port.length &&
Expand All @@ -28,6 +83,7 @@ function uploadImg(e) {
var link = a + e.message;
var t;
if (e.code == 1){
if (ms){
if (isImage) {
t = $(
'<div class="response-item response-success">上传成功,图片外链:<a target="_blank" href="' +
Expand All @@ -50,12 +106,12 @@ function uploadImg(e) {
link +
"</a></div>"
);
}
}}
resolve(e.message);
}else{
var t = $('<div class="response-item response-error">上传失败('+e.message+')</div>');
reject("上传失败(" + e.message + ")");
}


$("#response").prepend(t);
$("#uploadFile").val("");
$("#uploadFileLabel")
Expand All @@ -76,21 +132,20 @@ function uploadImg(e) {
copyButton.text(originalText);
}, 1000);
});
return e.message;
},
error: function () {
var errorResponse = $('<div class="response-item response-error">上传失败</div>');
$("#response").prepend(errorResponse);
reject("上传失败");
},
complete: function () {
$("#uploadButton").prop("disabled", !1);
$("#uploadButton").text("上传");
$("#loading").hide();
}
});
}
function isImageExtension(e) {
var o = e.substring(e.lastIndexOf("."));
return [".jpg", ".jpeg", ".png", ".gif", ".bmp"].includes(o.toLowerCase());
});
}
document.addEventListener("paste", function (e) {
for (var o = e.clipboardData.items, t = 0; t < o.length; t++) {
Expand All @@ -117,7 +172,7 @@ document.addEventListener("paste", function (e) {
}),
$("#uploadButton").click(function () {
var e = document.getElementById("uploadFile").files[0];
e ? uploadImg(e) : alert("请选择一个文件");
e ? uploadFile(e) : alert("请选择一个文件");
});
});
</script>
Expand Down
63 changes: 48 additions & 15 deletions control/control.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package control

import (
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net/http"
"path/filepath"
"regexp"
"strings"

"csz.net/tgstate/assets"
Expand Down Expand Up @@ -131,21 +133,52 @@ func D(w http.ResponseWriter, r *http.Request) {
log.Println("读取响应主体数据时发生错误:", err)
return
}
// 使用DetectContentType函数检测文件类型
rType = http.DetectContentType(buffer)
w.Header().Set("Content-Type", rType)
// 写入前512个字节到响应w
_, err = w.Write(buffer[:n])
if err != nil {
http.Error(w, "Failed to write content", http.StatusInternalServerError)
log.Println(http.StatusInternalServerError)
return
}
_, err = io.Copy(w, resp.Body)
if err != nil {
http.Error(w, "Failed to show content", http.StatusInternalServerError)
log.Println(http.StatusInternalServerError)
return
// 输出文件内容到控制台
if string(buffer[:12]) == "tgstate-blob" {
fmt.Println("这是一个分块文件")
content := string(buffer)
lines := strings.Fields(content)
fmt.Println("文件名:" + lines[1])
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename=\""+lines[1]+"\"")
for i := 2; i < len(lines); i++ {
fmt.Println("开始下载:" + lines[i])
fmt.Println("下载地址:" + utils.GetDownloadUrl(regexp.MustCompile("[^a-zA-Z0-9_]").ReplaceAllString(lines[i], "")))
blobResp, err := http.Get(utils.GetDownloadUrl(regexp.MustCompile("[^a-zA-Z0-9_]").ReplaceAllString(lines[i], "")))
if err != nil {
http.Error(w, "Failed to fetch content", http.StatusInternalServerError)
return
}

// 将文件名设置到Content-Disposition标头
blobResp.Header.Set("Content-Disposition", "attachment; filename=\""+lines[1]+"\"")

defer blobResp.Body.Close()

_, err = io.Copy(w, blobResp.Body)
if err != nil {
log.Println("写入响应主体数据时发生错误:", err)
return
}
}

} else {
// 使用DetectContentType函数检测文件类型
rType = http.DetectContentType(buffer)
w.Header().Set("Content-Type", rType)
// 写入前512个字节到响应w
_, err = w.Write(buffer[:n])
if err != nil {
http.Error(w, "Failed to write content", http.StatusInternalServerError)
log.Println(http.StatusInternalServerError)
return
}
_, err = io.Copy(w, resp.Body)
if err != nil {
http.Error(w, "Failed to show content", http.StatusInternalServerError)
log.Println(http.StatusInternalServerError)
return
}
}
}

Expand Down

0 comments on commit 31eca26

Please sign in to comment.