在Java Web开发中,使用JSP(JavaServer Pages)上传图片并即时显示效果是一个常见的需求。以下是一个简单的示例代码,展示了如何实现这一功能。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<h2>Upload Image</h2>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*" required>
<button type="submit">Upload</button>
</form>
</body>
</html>
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/upload")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "uploads";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) uploadDir.mkdir();
try {
Part filePart = request.getPart("image");
String fileName = getFileName(filePart);
String filePath = uploadPath + File.separator + fileName;
filePart.write(filePath);
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
request.setAttribute("imagePath", UPLOAD_DIRECTORY + "/" + fileName);
request.getRequestDispatcher("/result.jsp").forward(request, response);
} catch (Exception e) {
request.setAttribute("message", "There was an error: " + e.getMessage());
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Upload Result</title>
</head>
<body>
<h2>${message}</h2>
<c:if test="${not empty imagePath}">
<img src="${imagePath}" alt="Uploaded Image" width="300">
</c:if>
<a href="upload.jsp">Upload Another Image</a>
</body>
</html>
UPLOAD_DIRECTORY
路径正确且有写权限。通过以上代码和说明,你应该能够实现一个基本的JSP图片上传并即时显示的功能。如果有更多具体问题,可以根据错误信息进一步排查。
领取专属 10元无门槛券
手把手带您无忧上云