java实现文件上传下载
时间: 2023-09-02 12:08:52 浏览: 109
文件上传:
1. 创建一个表单,包含一个文件上传的input标签:
```html
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
```
2. 在服务器端创建一个Servlet处理上传的文件:
```java
public class UploadServlet extends HttpServlet {
public 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/uploaded/files/" + fileName));
IOUtils.copy(fileContent, out);
out.close();
}
}
```
文件下载:
1. 在服务器端创建一个Servlet处理下载请求:
```java
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取要下载的文件路径
String filePath = "/path/to/downloaded/files/file.txt";
File downloadFile = new File(filePath);
// 设置响应头
response.setContentType("application/octet-stream");
response.setContentLength((int) downloadFile.length());
response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadFile.getName() + "\"");
// 将文件写入输出流
FileInputStream in = new FileInputStream(downloadFile);
OutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
in.close();
out.close();
}
}
```
2. 在前端页面添加一个下载链接:
```html
<a href="download">下载文件</a>
```
其中,download是下载Servlet的映射路径。
阅读全文
相关推荐













