javaweb实现文件上传下载
时间: 2023-11-01 22:08:02 浏览: 108
文件上传和下载是Web应用程序中常见的功能之一,下面给出一个简单的JavaWeb实现:
1. 文件上传
在JSP页面中,需要一个表单,用于选择文件并提交:
```html
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
```
在Servlet中,处理文件上传的代码如下:
```java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取上传的文件
Part filePart = request.getPart("file");
String fileName = getFileName(filePart);
// 保存上传的文件
OutputStream out = new FileOutputStream(new File("D:/uploads/" + fileName));
InputStream in = filePart.getInputStream();
byte[] buffer = new byte[1024];
int length = -1;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
// 返回上传成功的信息
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.println("上传成功!");
}
// 获取上传的文件名
private String getFileName(Part part) {
String contentDisposition = part.getHeader("content-disposition");
String[] tokens = contentDisposition.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length() - 1);
}
}
return "";
}
```
2. 文件下载
在JSP页面中,需要一个超链接,用于触发文件下载:
```html
<a href="download?fileName=test.txt">Download</a>
```
在Servlet中,处理文件下载的代码如下:
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取要下载的文件名
String fileName = request.getParameter("fileName");
// 设置响应头,告诉浏览器下载文件
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
// 读取要下载的文件并写入响应流
InputStream in = new FileInputStream(new File("D:/uploads/" + fileName));
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
```
以上就是JavaWeb实现文件上传下载的简单示例,需要注意的是上传的文件保存在服务器的硬盘上,因此需要确保上传的文件不会对服务器造成安全威胁,如上传病毒文件、木马等。
阅读全文