Java 文件上传可以通过多种方式实现,其中最常见的是使用 Servlet 和 JSP。以下是一个简单的示例,演示如何使用 Servlet 和 JSP 实现文件上传:
- 创建一个 HTML 文件,用于上传文件:
<!DOCTYPE html>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
- 创建一个 Java Servlet,用于处理文件上传请求:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String savePath = "uploads/"; // 上传文件的保存路径
int maxFileSize = 5000 * 1024; // 上传文件的大小限制(单位:字节)
int maxMemSize = 5000 * 1024; // 内存缓存的大小限制(单位:字节)
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
File file = new File(savePath + File.separator + getFileName(httpRequest));
try (InputStream inputStream = httpRequest.getInputStream();
OutputStream outputStream = new FileOutputStream(file)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
response.getWriter().println("文件上传成功!");
} catch (IOException e) {
e.printStackTrace();
}
} else {
response.getWriter().println("无效的请求!");
}
}
private String getFileName(HttpServletRequest request) {
String fileName = request.getHeader("content-disposition").split(";")[1].split("\"")[1];
return fileName;
}
}
- 在 web.xml 中配置 Servlet:
<web-app>
<servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.example.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
</web-app>
- 部署应用程序并访问上传页面。
暂无回复。