javaweb文件上传下载
时间: 2023-08-04 10:12:56 浏览: 83
JavaWeb 文件上传下载可以通过以下步骤实现:
1. 文件上传
1.1 在表单中添加文件选择框
```html
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上传" />
</form>
```
1.2 编写上传文件的 Servlet
```java
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
InputStream fileContent = filePart.getInputStream();
// 处理上传的文件
}
}
```
2. 文件下载
2.1 在页面中添加下载链接
```html
<a href="download?fileName=example.txt">下载</a>
```
2.2 编写下载文件的 Servlet
```java
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileName = request.getParameter("fileName");
File file = new File("path/to/files/" + fileName);
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
try (InputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
}
}
```
以上就是 JavaWeb 文件上传下载的实现方法。
阅读全文