在Debian系統上,使用JSP實現文件上傳和下載需要以下幾個步驟:
確保你的Debian系統已經安裝了Java開發環境。如果沒有,請運行以下命令安裝:
sudo apt-get update
sudo apt-get install default-jdk
在Debian上安裝Tomcat服務器,可以使用以下命令:
sudo apt-get install tomcat9
編輯Tomcat的配置文件/etc/tomcat9/server.xml,在<Host>標簽內添加以下內容:
<Resource name="file" auth="Container" type="java.io.File" description="File Upload" driverClassName="org.apache.tomcat.jdbc.pool.DataSource" url="jdbc:h2:mem:testdb" username="sa" password="" maxActive="20" maxIdle="10" maxWait="-1"/>
在Tomcat的webapps目錄下創建一個名為file_upload_download.jsp的文件,然后添加以下內容:
<%@ page import="java.io.*, java.util.*, javax.servlet.*, javax.servlet.http.*, javax.servlet.annotation.*, org.apache.commons.fileupload.*, org.apache.commons.fileupload.disk.*, org.apache.commons.io.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>File Upload and Download</title>
</head>
<body>
<%
String uploadPath = application.getRealPath("") + "uploads";
File fileSaveDir = new File(uploadPath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
if (request.getMethod().equalsIgnoreCase("POST")) {
try {
Class.forName("org.apache.commons.fileupload.servlet.ServletFileUpload");
ServletFileUpload upload = new ServletFileUpload();
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
out.println("File " + fileName + " has uploaded successfully!");
}
}
}
} catch (Exception ex) {
out.println("There was an error: " + ex.getMessage());
}
}
%>
<form action="file_upload_download.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
<%
String downloadFileName = request.getParameter("download");
if (downloadFileName != null && !downloadFileName.isEmpty()) {
String filePath = uploadPath + File.separator + downloadFileName;
File fileToDownload = new File(filePath);
if (fileToDownload.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
FileInputStream inStream = new FileInputStream(fileToDownload);
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.flush();
}
}
%>
</body>
</html>
保存文件后,重啟Tomcat服務器以使更改生效:
sudo systemctl restart tomcat9
現在,你可以訪問http://your_server_ip:8080/file_upload_download.jsp來測試文件上傳和下載功能。請注意,這個示例使用了Apache Commons FileUpload庫,你可能需要將其添加到項目的依賴中。