在Java中,可以使用多种方法处理文件上传和下载。这里,我将向您展示如何使用Java Servlet来处理文件上传和下载。
首先,创建一个HTML表单,用于选择要上传的文件:
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="file" id="file">
<br><br>
<input type="submit" value="Upload">
</form>
</body>
</html>
接下来,创建一个名为FileUploadServlet
的Java Servlet,用于处理文件上传:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileUploadServlet extends HttpServlet {
private static final String UPLOAD_DIRECTORY = "uploads";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = getSubmittedFileName(filePart);
InputStream fileContent = filePart.getInputStream();
saveFile(fileName, fileContent);
response.sendRedirect("success.html");
}
private String getSubmittedFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
private void saveFile(String fileName, InputStream fileContent) throws IOException {
File uploadDir = new File(getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try (FileOutputStream fos = new FileOutputStream(new File(uploadDir, fileName))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileContent.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
}
}
创建一个名为FileDownloadServlet
的Java Servlet,用于处理文件下载:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileDownloadServlet extends HttpServlet {
private static final String FILE_DIRECTORY = "uploads";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
File file = new File(getServletContext().getRealPath("") + File.separator + FILE_DIRECTORY, fileName);
if (file.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, bytesRead);
}
}
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
}
现在,您可以在Web应用程序中使用这两个Servlet来处理文件上传和下载。请确保在web.xml
中配置这两个Servlet,以便它们可以正确处理请求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。