JSP(JavaServer Pages)文件上传至本地代码通常涉及到以下几个基础概念:
以下是一个简单的JSP文件上传示例:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>Upload File</h1>
<form action="uploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/uploadServlet")
@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("file");
String fileName = getFileName(filePart);
String filePath = uploadPath + File.separator + fileName;
filePart.write(filePath);
response.getWriter().println("File " + fileName + " has uploaded successfully!");
} catch (Exception e) {
response.getWriter().println("There was an error: " + e.getMessage());
}
}
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;
}
}
@MultipartConfig
注解中的fileSizeThreshold
、maxFileSize
和maxRequestSize
参数。filePart.getContentType()
来验证文件类型。uploadPath
正确,并且有写权限。通过以上步骤和示例代码,可以实现基本的JSP文件上传功能。如果遇到具体问题,可以根据错误信息进行调试和解决。
领取专属 10元无门槛券
手把手带您无忧上云