JSP(JavaServer Pages)是一种用于创建动态Web内容的Java技术。下面是一个简单的JSP上传和下载图片的示例代码。
首先,创建一个HTML表单用于上传图片:
<!DOCTYPE html>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<h1>Upload Image</h1>
<form action="uploadImage.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*" required>
<input type="submit" value="Upload">
</form>
</body>
</html>
创建一个JSP页面来处理文件上传:
<%@ page import="java.io.*, java.util.*, javax.servlet.http.*, javax.servlet.*" %>
<%@ page import="org.apache.commons.fileupload.*, org.apache.commons.fileupload.disk.*, org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>
<%
String uploadPath = application.getRealPath("") + File.separator + "uploads";
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) uploadDir.mkdir();
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(uploadPath + File.separator + name));
out.println("File " + name + " has uploaded successfully!");
}
}
} catch (Exception ex) {
out.println("There was an error: " + ex.getMessage());
}
%>
创建一个HTML页面,提供下载链接:
<!DOCTYPE html>
<html>
<head>
<title>Download Image</title>
</head>
<body>
<h1>Download Image</h1>
<a href="downloadImage.jsp?filename=image.jpg">Download image.jpg</a>
</body>
</html>
创建一个JSP页面来处理文件下载:
<%@ page import="java.io.*" %>
<%
String filePath = application.getRealPath("") + File.separator + "uploads" + File.separator + request.getParameter("filename");
File file = new File(filePath);
if (file.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
try (InputStream in = new FileInputStream(file);
OutputStream outStream = response.getOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
out.println("Error: " + e.getMessage());
}
} else {
out.println("File not found!");
}
%>
<multipart-config>
标签或在服务器端配置文件中调整上传文件的大小限制。通过以上步骤,你可以实现基本的图片上传和下载功能。在实际应用中,可能需要根据具体需求进行调整和优化。
领取专属 10元无门槛券
手把手带您无忧上云