jsp 文件上传下载代码
时间: 2023-08-25 16:06:10 浏览: 97
以下是 JSP 文件上传下载的示例代码:
文件上传:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.*, java.util.*, javax.servlet.*,
javax.servlet.http.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<h1>文件上传</h1>
<form action="upload.jsp" method="post" enctype="multipart/form-data">
<label for="file">选择文件:</label>
<input type="file" id="file" name="file"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
<%
// 处理文件上传
if (request.getMethod().equalsIgnoreCase("POST")) {
// 获取文件保存路径
String savePath = getServletContext().getRealPath("/uploads");
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
// 获取上传的文件
Part filePart = request.getPart("file");
String fileName = getFileName(filePart);
// 保存文件
OutputStream out = new FileOutputStream(new File(saveDir, fileName));
InputStream in = filePart.getInputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
out.println("文件上传成功!");
}
// 获取上传文件名
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length() - 1);
}
}
return "";
}
%>
```
文件下载:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.*, javax.servlet.*,
javax.servlet.http.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
<h1>文件下载</h1>
<form action="download.jsp" method="post">
<label for="fileName">输入文件名:</label>
<input type="text" id="fileName" name="fileName"><br>
<input type="submit" value="下载">
</form>
</body>
</html>
<%
// 处理文件下载
if (request.getMethod().equalsIgnoreCase("POST")) {
// 获取文件保存路径
String savePath = getServletContext().getRealPath("/uploads");
String fileName = request.getParameter("fileName");
// 下载文件
File file = new File(savePath, fileName);
if (file.exists() && file.isFile()) {
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int len = 0;
while ((len = bis.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
bis.close();
fis.close();
os.flush();
os.close();
}
else {
out.println("文件不存在!");
}
}
%>
```
这里的示例将上传的文件保存到 "/uploads" 目录下,可以根据实际情况修改保存路径。另外,文件下载需要根据上传时的文件名进行下载,因此需要在文件上传时保存文件名。
阅读全文