给出Java web servlet文件上传与下载示例
时间: 2024-12-08 14:20:06 浏览: 8
在Java Web中,使用Servlet进行文件上传和下载的基本步骤如下:
**文件上传示例(使用HttpServletRequest和HttpServletResponse)**:
```java
import javax.servlet.*;
import java.io.*;
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取上传文件的参数
String filePart = "file"; // 这通常是form表单中的file字段名
Part filePartObj = request.getPart(filePart);
if (filePartObj != null) {
// 创建临时目录存储文件
File dir = new File("uploads");
if (!dir.exists()) {
dir.mkdir();
}
// 获取文件名称和保存路径
String fileName = Paths.get(dir.getAbsolutePath(), filePartObj.getName()).toString();
// 将文件保存到服务器上
InputStream inputStream = filePartObj.getInputStream();
OutputStream outputStream = new FileOutputStream(fileName);
byte[] buffer = new byte[4096];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
}
// 返回成功响应
response.getWriter().println("File uploaded successfully.");
}
}
```
**文件下载示例(使用ServletOutputStream)**:
```java
import javax.servlet.*;
import java.io.*;
public class FileDownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filePath = "/path/to/downloaded/file.txt"; // 替换为你实际的文件路径
// 设置响应头信息,告知浏览器这是一个文件下载
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=file.txt");
// 读取文件内容并发送给浏览器
FileInputStream fis = new FileInputStream(filePath);
ServletOutputStream sos = response.getOutputStream();
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) != -1) {
sos.write(bytes, 0, length);
}
fis.close();
sos.flush();
sos.close();
}
}
```
阅读全文