jinlin
2025-03-22 b20c16dd6c9fd19a44afe2b082c2fa5ff8945aaa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package com.example.client.utils;
 
import com.example.server.progressTrack.model.DjJdgzNetworkLevel3;
import com.example.server.progressTrack.model.DjJdgzTrackRecord;
import com.example.server.sysOss.model.SysOss;
import com.example.server.sysOss.service.OssEncryptService;
import com.example.server.sysOss.service.SysOssService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
@Service
public class UploadFile {
    private File[] selectedFiles;
    @Autowired
    private SysOssService sysOssService;
    @Autowired
    private OssEncryptService ossEncryptService;
    private List<SysOss> ossList;
    private SysOss templet;
 
    @Value("${zt.oss.local-path}")
    private String localPath;
    private static final String key = "zhpt-key#%W";
 
    public JPanel uploadFile(JFrame frame, Integer width, Integer heigth, SysOss sysOssTemplet) {
        JPanel jPanel = new JPanel();
        jPanel.setPreferredSize(new Dimension(width, heigth));
 
        templet = sysOssTemplet;
        if (sysOssTemplet.getBusiId() != null) {
            ossList = sysOssService.getList(sysOssTemplet.getBusiId(), sysOssTemplet.getBusiType());
        } else {
            ossList = new ArrayList<>();
        }
 
        JTable table = new JTable();
        table.setRowHeight(10);
        DefaultTableModel model = new DefaultTableModel();
        String[] columnIdentifiers = {"文件地址", "操作"};//表头
 
        JScrollPane scrolltable = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrolltable.setPreferredSize(new Dimension(width, heigth - 100));
        scrolltable.setViewportView(table);
        scrolltable.getViewport().setBackground(Color.WHITE);
 
 
        JButton browseButton = new JButton("选择文件");
        jPanel.add(browseButton);
        jPanel.add(scrolltable);
        if (ossList != null && ossList.size() > 0) {
            String[][] data = new String[ossList.size()][2];
            for (int i = 0; i < ossList.size(); i++) {
                data[i][0] = ossList.get(i).getName();
            }
 
            model.setDataVector(data, columnIdentifiers);
            table.setModel(model);
            table.getColumnModel().getColumn(0).setPreferredWidth(width - 120);
            table.getColumnModel().getColumn(1).setPreferredWidth(120);
 
            table.getColumnModel().getColumn(0).setCellRenderer(new TableViewRenderer());
            table.getColumnModel().getColumn(1).setCellRenderer(new TableCellRendererButton());
            table.getColumnModel().getColumn(1).setCellEditor(new TableCellEditorButton(ossList, sysOssService));
 
        }
 
        final boolean[] historyCalled = {false};
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (historyCalled[0]) return;
                // 获取点击的行和列
                int row = table.rowAtPoint(e.getPoint());
                int column = table.columnAtPoint(e.getPoint());
 
                // 检查是否点击了有效单元格
                if (row >= 0 && column >= 0) {
                    if (column == 0) { // 列索引从0开始
                        String path = ossList.get(row).getPath();
                        String name = ossList.get(row).getName();
                        File file = new File(localPath + path);
                        InputStream is = null;
 
                        try {
                            is = ossEncryptService.decryptStream(file, ossEncryptService.getKey(key));
 
                            // 创建文件选择器并设置初始文件名
                            JFileChooser fileChooser = new JFileChooser();
                            fileChooser.setSelectedFile(new File(name)); // 设置默认文件名
 
                            int result = fileChooser.showSaveDialog(frame);
 
                            if (result == JFileChooser.APPROVE_OPTION) {
                                File selectedFile = fileChooser.getSelectedFile();
 
                                // 将 InputStream 的内容写入到 selectedFile
                                try (InputStream input = is;
                                     OutputStream output = new FileOutputStream(selectedFile)) {
 
                                    byte[] buffer = new byte[8192]; // 缓冲区大小
                                    int bytesRead;
                                    while ((bytesRead = input.read(buffer)) != -1) {
                                        output.write(buffer, 0, bytesRead);
                                    }
 
                                    // 文件保存成功
                                    JOptionPane.showMessageDialog(frame, "文件下载成功");
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                    JOptionPane.showMessageDialog(frame, "文件保存失败: " + ex.getMessage());
                                }
                            } else {
                                JOptionPane.showMessageDialog(frame, "文件下载取消");
                            }
                        } catch (Exception exception) {
                            exception.printStackTrace();
                        } finally {
                            // 确保 InputStream 被关闭,避免资源泄露
                            if (is != null) {
                                try {
                                    is.close();
                                } catch (IOException ec) {
                                    ec.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        });
 
        browseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Boolean flag = true;
                // 保存当前的外观设置
                LookAndFeel savedLookAndFeel = UIManager.getLookAndFeel();
 
                // 设置文件选择器外观
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
 
                JFileChooser fileChooser = new JFileChooser();
 
                fileChooser.setDialogTitle("选择文件");
                fileChooser.setPreferredSize(new Dimension(800, 500));
 
 
                fileChooser.setMultiSelectionEnabled(true);
 
                //恢复外观,避免改变所有组件外观
                try {
                    UIManager.setLookAndFeel(savedLookAndFeel);
                } catch (UnsupportedLookAndFeelException ed) {
                    ed.printStackTrace();
                }
 
                int result = fileChooser.showOpenDialog(frame);
                if (result == JFileChooser.FILES_ONLY) {
                    selectedFiles = fileChooser.getSelectedFiles();
 
                    Integer oldNum = model.getRowCount();
                    String[][] data = new String[oldNum + selectedFiles.length][2];
                    for (int i = 0; i < oldNum; i++) {
                        data[i][0] = model.getValueAt(i, 0).toString();
                    }
                    for (int i = 0; i < selectedFiles.length; i++) {
                        data[i + oldNum][0] = selectedFiles[i].getPath();
                        String suffix = selectedFiles[i].getName().substring(selectedFiles[i].getName().lastIndexOf("."));
                        SysOss oss = null;
                        try {
                            oss = templet.clone();
                        } catch (CloneNotSupportedException cloneNotSupportedException) {
                            cloneNotSupportedException.printStackTrace();
                        }
                        oss.setType(suffix);
                        oss.setPath(selectedFiles[i].getPath());
                        oss.setName(selectedFiles[i].getName());
                        ossList.add(oss);
                    }
 
                    model.setDataVector(data, columnIdentifiers);
                    table.setModel(model);
                    table.getColumnModel().getColumn(0).setPreferredWidth(width - 120);
                    table.getColumnModel().getColumn(1).setPreferredWidth(120);
 
 
                    table.getColumnModel().getColumn(0).setCellRenderer(new TableViewRenderer());
                    table.getColumnModel().getColumn(1).setCellRenderer(new TableCellRendererButton());
                    table.getColumnModel().getColumn(1).setCellEditor(new TableCellEditorButton(ossList, sysOssService));
 
                } else {
                    Object[] options = {"OK ", "CANCEL "};
                    JOptionPane.showOptionDialog(null, "选择的文件不正确 ", "提示", JOptionPane.DEFAULT_OPTION,
                            JOptionPane.WARNING_MESSAGE, null, options, options[0]);
                }
            }
        });
 
 
        scrolltable.setTransferHandler(new TransferHandler() {
            private static final long serialVersionUID = 1L;
 
            @Override
            public boolean importData(JComponent comp, Transferable t) {
                try {
                    Object o = t.getTransferData(DataFlavor.javaFileListFlavor);
                    String filepath = o.toString();
                    if (filepath.startsWith("[")) {
                        filepath = filepath.substring(1);
                    }
                    if (filepath.endsWith("]")) {
                        filepath = filepath.substring(0, filepath.length() - 1);
                    }
                    String[] filepathArr = filepath.split(", ");
                    Integer oldNum = model.getRowCount();
                    String[][] data = new String[oldNum + filepathArr.length][2];
                    for (int i = 0; i < oldNum; i++) {
                        data[i][0] = model.getValueAt(i, 0).toString();
                    }
                    for (int i = 0; i < filepathArr.length; i++) {
                        data[i + oldNum][0] = filepathArr[i];
                        SysOss oss = null;
                        try {
                            oss = templet.clone();
                        } catch (CloneNotSupportedException cloneNotSupportedException) {
                            cloneNotSupportedException.printStackTrace();
                        }
                        int lastSlashIndex = filepathArr[i].lastIndexOf('/');
                        String fullFileName = "";
                        if (lastSlashIndex != -1) {
                            fullFileName = filepathArr[i].substring(lastSlashIndex + 1);
                        }
                        oss.setPath(filepathArr[i]);
                        oss.setName(fullFileName);
                        ossList.add(oss);
                    }
                    model.setDataVector(data, columnIdentifiers);
                    table.setModel(model);
                    table.getColumnModel().getColumn(0).setPreferredWidth(width - 120);
                    table.getColumnModel().getColumn(1).setPreferredWidth(120);
 
                    table.getColumnModel().getColumn(0).setCellRenderer(new TableViewRenderer());
                    table.getColumnModel().getColumn(1).setCellRenderer(new TableCellRendererButton());
                    table.getColumnModel().getColumn(1).setCellEditor(new TableCellEditorButton(ossList, sysOssService));
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }
 
            @Override
            public boolean canImport(JComponent comp, DataFlavor[] flavors) {
                for (int i = 0; i < flavors.length; i++) {
                    if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
                        return true;
                    }
                }
                return false;
            }
        });
        return jPanel;
    }
 
    public void save(Long id) {
        if (ossList != null && ossList.size() > 0) {
            for (SysOss oss : ossList) {
                if (oss.getBusiId()==null){
                    oss.setBusiId(id);
                }
                if (oss.getId() == null) {
                    sysOssService.upload(oss);
                }
            }
        }
    }
}