在Java中,我们可以使用Servlet和Apache Commons FileUpload库来实现文件上传和进度显示。以下是一个简单的示例:
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
FileUploadServlet
的类:import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
InputStream inputStream = item.openStream();
OutputStream outputStream = Files.newOutputStream(Paths.get("uploads/" + fileName));
byte[] buffer = new byte[1024];
int bytesRead;
long totalBytesRead = 0;
long fileSize = item.getSize();
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
// 计算并显示上传进度
int progress = (int) ((totalBytesRead / (float) fileSize) * 100);
System.out.println("Upload progress: " + progress + "%");
}
inputStream.close();
outputStream.close();
}
}
} catch (Exception e) {
throw new ServletException("Error uploading file", e);
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
现在,当你运行这个应用并尝试上传一个文件时,控制台将显示文件上传的进度。请注意,这个示例仅在控制台显示上传进度,实际应用中你可能需要将进度信息发送到客户端以在网页上显示。要实现这一点,你可以使用WebSockets或其他技术(如AJAX)来实时更新客户端的进度条。