(目录)
Java可以使用Swing的JProgressBar组件来实现带进度条的上传功能。
以下是一个简单的示例代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileUploadWithProgressBar extends JFrame {
private JLabel label;
private JProgressBar progressBar;
private JButton uploadButton;
public FileUploadWithProgressBar() {
setTitle("文件上传");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
label = new JLabel("选择文件:");
progressBar = new JProgressBar(0, 100);
uploadButton = new JButton("上传");
add(label);
add(progressBar);
add(uploadButton);
uploadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("选择文件");
int selection = fileChooser.showOpenDialog(null);
if (selection == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
uploadFile(file);
}
}
});
}
private void uploadFile(File file) {
SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
@Override
protected Void doInBackground() throws Exception {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
long fileSize = file.length();
long uploadedSize = 0;
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream("path/to/save/file");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
uploadedSize += bytesRead;
int progress = (int) (uploadedSize * 100 / fileSize);
publish(progress);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
return null;
}
@Override
protected void process(java.util.List<Integer> chunks) {
int progress = chunks.get(chunks.size() - 1);
progressBar.setValue(progress);
}
@Override
protected void done() {
progressBar.setValue(100);
JOptionPane.showMessageDialog(null, "文件上传完成!");
}
};
worker.execute();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
FileUploadWithProgressBar frame = new FileUploadWithProgressBar();
frame.setVisible(true);
}
});
}
}
通过使用Swing的JProgressBar组件显示上传进度,并使用SwingWorker来在后台线程中执行文件上传操作。在doInBackground()方法中,通过FileInputStream读取文件内容,并通过FileOutputStream将文件内容写入到指定路径。在每次写入文件内容之后,使用publish()方法来更新上传进度,然后在process()方法中更新进度条的值。最后,在done()方法中设置进度条的值为100,并弹出提示框显示上传完成的消息,代码中的"path/to/save/file"替换保存文件的路径。