javaweb文件上传下载
时间: 2023-08-29 21:13:39 浏览: 75
javaWeb文件的上传下载
5星 · 资源好评率100%
JavaWeb 文件上传下载可以使用 Servlet 和 JSP 技术实现,下面是一个简单的示例代码:
文件上传:
1. 在 JSP 页面中添加一个表单,用于选择文件并提交表单:
```html
<form action="upload" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
```
2. 在 Servlet 中处理文件上传请求,将文件保存到服务器指定目录:
```java
@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取上传的文件
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
InputStream fileContent = filePart.getInputStream();
// 将文件保存到服务器指定目录
OutputStream out = new FileOutputStream(new File("/path/to/upload/dir", fileName));
byte[] buffer = new byte[1024];
int len;
while ((len = fileContent.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
fileContent.close();
response.getWriter().println("File " + fileName + " uploaded successfully.");
}
}
```
文件下载:
1. 在 JSP 页面中添加一个下载链接,点击链接即可下载文件:
```html
<a href="download?fileName=file.txt">Download file</a>
```
2. 在 Servlet 中处理下载请求,将文件发送给客户端:
```java
@WebServlet("/download")
public class FileDownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取要下载的文件名
String fileName = request.getParameter("fileName");
// 获取要下载的文件路径
String filePath = "/path/to/download/dir/" + fileName;
// 设置响应内容类型
response.setContentType("application/octet-stream");
// 设置响应头信息
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
// 读取要下载的文件,并将内容写入响应输出流中
FileInputStream in = new FileInputStream(new File(filePath));
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
}
}
```
以上代码仅为示例,实际应用中需要根据具体需求进行调整。
阅读全文