Java实现网盘上传下载共享,手把手搭建Java共享网盘
时间: 2024-01-06 21:04:58 浏览: 122
好的,我可以为你提供一些基本的步骤来手把手搭建一个Java共享网盘。
1.准备工作
在开始之前,你需要安装以下软件:
- JDK
- Tomcat
- MySQL
- Maven
2.创建MySQL数据库
首先,你需要在MySQL中创建一个数据库来存储文件和用户信息。可以使用以下命令创建一个新的数据库:
```
CREATE DATABASE netdisk;
```
然后,你需要在该数据库中创建两个表:一个用于存储用户信息,另一个用于存储文件信息。
用户表:
```
CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
```
文件表:
```
CREATE TABLE files (
id INT NOT NULL AUTO_INCREMENT,
filename VARCHAR(255) NOT NULL,
filepath VARCHAR(255) NOT NULL,
owner_id INT NOT NULL,
shared TINYINT(1) NOT NULL DEFAULT 0,
PRIMARY KEY (id),
FOREIGN KEY (owner_id) REFERENCES users(id)
);
```
3.创建Java Web项目
使用Maven创建一个新的Java Web项目。在pom.xml文件中添加以下依赖项:
```
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
```
4.编写Java代码
现在,你可以开始编写Java代码了。创建一个名为FileUploadServlet的Java Servlet来处理文件上传请求。你需要在web.xml文件中指定Servlet映射。
```
<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>
```
在FileUploadServlet中,你需要实现doPost()方法来处理文件上传请求。你需要使用Apache Commons FileUpload库来解析上传的文件。
```
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
String filename = item.getName();
String filepath = "/uploads/" + UUID.randomUUID().toString() + "/" + filename;
File file = new File(getServletContext().getRealPath(filepath));
file.getParentFile().mkdirs();
item.write(file);
// Save file info to database
int ownerId = Integer.parseInt(request.getParameter("ownerId"));
saveFile(filename, filepath, ownerId);
}
}
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to upload file");
e.printStackTrace();
}
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
```
5.实现文件下载和共享功能
你还可以实现文件下载和共享功能。创建一个名为FileDownloadServlet的Java Servlet来处理文件下载请求。在响应中设置Content-Disposition头文件来指定文件名。
```
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filepath = request.getParameter("filepath");
File file = new File(getServletContext().getRealPath(filepath));
String filename = file.getName();
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
response.setContentLength((int) file.length());
FileInputStream fileInputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
outputStream.close();
}
```
对于共享文件,你需要在文件表中添加一个shared列。创建一个名为FileShareServlet的Java Servlet来处理共享文件请求。在请求中将shared列设置为1。
```
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int fileId = Integer.parseInt(request.getParameter("fileId"));
shareFile(fileId);
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
```
6.创建用户登录和注册页面
最后,你需要为用户提供登录和注册页面。创建一个名为login.jsp的JSP页面来显示登录表单。
```
<form method="post" action="LoginServlet">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit">Login</button>
</form>
```
创建一个名为register.jsp的JSP页面来显示注册表单。
```
<form method="post" action="RegisterServlet">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit">Register</button>
</form>
```
7.实现用户验证和会话管理
最后,你需要实现用户验证和会话管理。创建一个名为LoginServlet的Java Servlet来验证用户登录请求。在验证成功后,将用户ID存储到会话中。
```
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
int userId = authenticateUser(username, password);
if (userId > 0) {
HttpSession session = request.getSession(true);
session.setAttribute("userId", userId);
response.sendRedirect(request.getContextPath() + "/index.jsp");
} else {
response.sendRedirect(request.getContextPath() + "/login.jsp?error=1");
}
}
```
创建一个名为LogoutServlet的Java Servlet来处理用户注销请求。在会话中删除用户ID。
```
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute("userId");
session.invalidate();
}
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
```
现在,你已经完成了手把手搭建Java共享网盘的所有步骤!
阅读全文