下面是使用Commons FileUpload实现Java文件上传的完整攻略:
前提条件
在使用Commons FileUpload之前,需要确保你已经满足以下的条件:
-
已经安装了Java SDK(至少是1.6或以上版本)
-
已经使用Eclipse等集成开发环境,或者手动配置好了Java的CLASSPATH。
-
已经有一个能够接受文件上传请求的Java Web应用程序。
Step 1:引入Commons FileUpload
你需要下载并将Commons FileUpload JAR包导入到你的Java Web应用程序中,这样才能在Java代码中使用它提供的API。
在Maven项目中,你可以通过以下方式引入依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
在普通的Java Web应用程序中,你可以从Apache的官网下载最新版本的JAR包,并将它们拷贝到你的WEB-INF/lib目录中。
Step 2:实现文件上传的Servlet
接下来,你需要创建一个Servlet,用于接收上传的文件。在Servlet中,你需要实现以下的步骤:
-
检查请求中是否包含上传的文件。如果不包含,直接返回错误提示。
-
解析上传的文件内容。这会输出一个FileItem对象数组。
-
迭代这个数组,将上传的每个文件保存到磁盘上。
下面是一个示例Servlet代码:
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/FileUploadServlet")
public class FileUploadServlet 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 {
// 检查是否为文件上传请求
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是,则返回错误提示
PrintWriter writer = response.getWriter();
writer.println("Error: Please specify enctype='multipart/form-data' in your form.");
writer.flush();
return;
}
// 创建一个DiskFileItemFactory,用于解析上传的文件内容
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置缓存大小
factory.setSizeThreshold(1024 * 1024 * 10); // 10MB
// 设置临时目录
File tempDir = new File(System.getProperty("java.io.tmpdir"));
factory.setRepository(tempDir);
// 初始化ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置上传文件大小的限制
upload.setFileSizeMax(1024 * 1024 * 100); // 100MB
// 设置上传内容大小的限制
upload.setSizeMax(1024 * 1024 * 150); // 150MB
// 设置上传文件存储的目录
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
// 确保目录存在
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
// 解析上传内容
try {
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 循环遍历每个文件项
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在服务器中保存文件
item.write(storeFile);
request.setAttribute("message", "File " + fileName + " has uploaded successfully.");
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
// 返回成功提示
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
}
示例 1:基本上传
下面是一个基本文件上传的示例代码,包括一个上传文件的HTML表单和用于接收上传的Servlet。该示例将上传的文件保存在指定目录下:
HTML Form
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
Servlet
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadServlet 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 {
// 检查是否为文件上传请求
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是,则返回错误提示
PrintWriter writer = response.getWriter();
writer.println("Error: Please specify enctype='multipart/form-data' in your form.");
writer.flush();
return;
}
// 创建一个DiskFileItemFactory,用于解析上传的文件内容
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置缓存大小
factory.setSizeThreshold(1024 * 1024 * 10); // 10MB
// 设置临时目录
File tempDir = new File(System.getProperty("java.io.tmpdir"));
factory.setRepository(tempDir);
// 初始化ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置上传文件大小的限制
upload.setFileSizeMax(1024 * 1024 * 100); // 100MB
// 设置上传内容大小的限制
upload.setSizeMax(1024 * 1024 * 150); // 150MB
// 设置上传文件存储的目录
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
// 确保目录存在
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
// 解析上传内容
try {
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 循环遍历每个文件项
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在服务器中保存文件
item.write(storeFile);
request.setAttribute("message", "File " + fileName + " has uploaded successfully.");
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
// 返回成功提示
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
}
示例 2:限制上传文件类型
下面是一个示例代码,用于在上传文件时限制文件类型:
HTML Form
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
Servlet
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "uploads";
private static final String[] ALLOWED_FILE_TYPES = new String[]{"jpg", "jpeg", "png", "gif"};
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 检查是否为文件上传请求
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是,则返回错误提示
PrintWriter writer = response.getWriter();
writer.println("Error: Please specify enctype='multipart/form-data' in your form.");
writer.flush();
return;
}
// 创建一个DiskFileItemFactory,用于解析上传的文件内容
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置缓存大小
factory.setSizeThreshold(1024 * 1024 * 10); // 10MB
// 设置临时目录
File tempDir = new File(System.getProperty("java.io.tmpdir"));
factory.setRepository(tempDir);
// 初始化ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置上传文件大小的限制
upload.setFileSizeMax(1024 * 1024 * 100); // 100MB
// 设置上传内容大小的限制
upload.setSizeMax(1024 * 1024 * 150); // 150MB
// 设置上传文件存储的目录
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
// 确保目录存在
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
// 解析上传内容
try {
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 循环遍历每个文件项
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!isValidFileType(fileExtension)) {
// 如果上传的文件类型不在指定范围内,则返回错误提示
PrintWriter writer = response.getWriter();
writer.println("Error: File type " + fileExtension + " is not allowed.");
writer.flush();
return;
}
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在服务器中保存文件
item.write(storeFile);
request.setAttribute("message", "File " + fileName + " has uploaded successfully.");
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
// 返回成功提示
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
private boolean isValidFileType(String fileExtension) {
for (String allowedFileType : ALLOWED_FILE_TYPES) {
if (allowedFileType.equalsIgnoreCase(fileExtension)) {
return true;
}
}
return false;
}
}
在上面的示例代码中,我们添加了一个isValidFileType()方法,用于检查上传的文件类型是否为允许的文件类型。如果上传的文件类型不在指定范围内,我们将输出一个错误提示,并且不会保存上传的文件。
希望这个攻略可以帮助到你~
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java使用common-fileupload实现文件上传 - Python技术站