jokyo3 commited on
Commit
a48defc
·
verified ·
1 Parent(s): 632819a

Create imageUpload.js

Browse files
Files changed (1) hide show
  1. imageUpload.js +91 -0
imageUpload.js ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // 假设页面已经加载了image-compression库
2
+
3
+ // JavaScript函数,用于上传图片并返回完整的URL地址
4
+ function uploadImagesAndGetFullUrls(fileInputId, uploadEndpoint, hostUrl) {
5
+ const fileInput = document.getElementById(fileInputId);
6
+ const files = fileInput.files;
7
+ const formData = new FormData();
8
+
9
+ // 图片压缩功能
10
+ function compressImage(file) {
11
+ const options = {
12
+ maxSizeMB: 5, // 最大文件大小
13
+ maxWidthOrHeight: 1920, // 图片最大宽度或高度
14
+ useWebWorker: true
15
+ };
16
+
17
+ return imageCompression(file, options)
18
+ .then(compressedFile => {
19
+ console.log(`原始文件大小:${file.size / 1024 / 1024} MB`);
20
+ console.log(`压缩后文件大小:${compressedFile.size / 1024 / 1024} MB`);
21
+ return compressedFile;
22
+ })
23
+ .catch(error => {
24
+ console.error('图片压缩失败:', error);
25
+ return file; // 如果压缩失败,返回原始文件
26
+ });
27
+ }
28
+
29
+ // 处理所有选中的文件
30
+ const compressPromises = Array.from(files).map(compressImage);
31
+
32
+ return Promise.all(compressPromises)
33
+ .then(compressedFiles => {
34
+ compressedFiles.forEach(compressedFile => {
35
+ formData.append('file[]', compressedFile);
36
+ });
37
+
38
+ return fetch(`${hostUrl}${uploadEndpoint}`, {
39
+ method: 'POST',
40
+ body: formData
41
+ });
42
+ })
43
+ .then(response => {
44
+ if (!response.ok) {
45
+ throw new Error('网络响应不是OK状态');
46
+ }
47
+ return response.json();
48
+ })
49
+ .then(data => {
50
+ if (data.error) {
51
+ throw new Error(data.error);
52
+ }
53
+ return data.map(item => `${hostUrl}${item.src}`);
54
+ });
55
+ }
56
+
57
+ // 定义host URL和上传端点
58
+ const hostUrl = 'https://upimg.wook.eu.org';
59
+ const uploadEndpoint = '/upload';
60
+
61
+ // 在文档加载完成后添加事件监听器
62
+ document.addEventListener('DOMContentLoaded', function() {
63
+ const form = document.querySelector('form');
64
+ const urlTextArea = document.querySelector('textarea[name="imageUrls"]');
65
+ const fileInput = document.getElementById('imageFileInput');
66
+
67
+ form.addEventListener('submit', function(event) {
68
+ // 检查URL文本区域是否为空
69
+ if (urlTextArea.value.trim() === '' && fileInput.files.length > 0) {
70
+ // 阻止表单的默认提交行为
71
+ event.preventDefault();
72
+
73
+ // 调用函数上传图片并获取URL
74
+ uploadImagesAndGetFullUrls('imageFileInput', uploadEndpoint, hostUrl)
75
+ .then(fullUrls => {
76
+ // 将获取到的URLs添加到文本区域
77
+ urlTextArea.value = fullUrls.join('\n');
78
+
79
+ // 使用新的URLs重新提交表单
80
+ form.submit();
81
+ })
82
+ .catch(error => {
83
+ console.error('上传失败:', error);
84
+ });
85
+ }
86
+ });
87
+ });
88
+
89
+ function confirmDelete() {
90
+ return confirm('确定要删除这张图片吗?');
91
+ }