java文件上传工具类
时间: 2023-08-24 19:06:10 浏览: 122
java 上传文件工具类 java 上传文件工具类
您可以使用Apache Commons FileUpload来实现Java文件上传的工具类。该工具类可以将文件上传到服务器,并提供丰富的上传控制和进度报告。以下是一个简单的Java文件上传工具类的示例代码:
```
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
public class FileUploadUtils {
public static final String UPLOAD_DIRECTORY = "uploads";
public static boolean uploadFiles(HttpServletRequest request) {
File uploadDir = new File(UPLOAD_DIRECTORY);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return false;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = UPLOAD_DIRECTORY + File.separator + fileName;
File uploadedFile = new File(filePath);
item.write(uploadedFile);
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
```
请注意,该示例代码需要进行适当调整以适应您的应用程序。
阅读全文