在Java中實(shí)現(xiàn)文件上傳功能,通??梢允褂肧ervlet和MultipartRequest類
pom.xml
文件中(如果你使用的是Maven項(xiàng)目): <groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
FileUploadServlet
的類,并繼承HttpServlet
類:import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 處理文件上傳邏輯
}
}
doPost
方法中,使用ServletFileUpload
類來解析請(qǐng)求,并獲取上傳的文件。例如:protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(request)) {
throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
}
ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
PrintWriter writer = response.getWriter();
response.setContentType("text/plain");
try {
List<FileItem> items = uploadHandler.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
// 處理文件上傳
String fileName = item.getName();
InputStream fileContent = item.getInputStream();
// 保存文件到服務(wù)器
saveFile(fileContent, fileName);
}
}
writer.write("File uploaded successfully!");
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
writer.close();
}
saveFile
方法,將上傳的文件保存到服務(wù)器的指定位置。例如:private void saveFile(InputStream fileContent, String fileName) throws IOException {
String filePath = "/path/to/your/upload/directory/" + fileName;
File fileToSave = new File(filePath);
try (FileOutputStream outputStream = new FileOutputStream(fileToSave)) {
int read;
byte[] bytes = new byte[1024];
while ((read = fileContent.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
}
web.xml
文件中配置你的Servlet,以便在接收到文件上傳請(qǐng)求時(shí)調(diào)用它。例如: <servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.example.FileUploadServlet</servlet-class>
</servlet><servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
現(xiàn)在,當(dāng)用戶通過表單提交文件時(shí),你的應(yīng)用程序?qū)⒛軌蛱幚砦募蟼髡?qǐng)求,并將文件保存到服務(wù)器的指定位置。