为什么在尝试将图像加载到 Java 数据库时会出现此错误?
这是代码:
boolean estado = false;
ArrayList<String> lista = new ArrayList<>();
try {
FileItemFactory file = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(file);
List items = fileUpload.parseRequest((RequestContext) request);
for (int i = 0; i < items.size(); i++) {
FileItem fileItems = (FileItem) items.get(i);
if (!fileItems.isFormField()) {
File f = new File("C:\\images\\" + fileItems.getName());
fileItems.write(f);
dtoFotos.setRuta(f.getAbsolutePath());
} else {
lista.add(fileItems.getString());
}
}
estado = daoFotos.insertarFoto(dtoFotos);
} catch (Exception e) {
System.out.println(e);
request.setAttribute("message", e);
}
我收到此错误:
<块引用>java.lang.ClassCastException: org.apache.catalina.connector.RequestFacade 不能转换为 org.apache.tomcat.util.http.fileupload.RequestContext
我该如何解决这个问题?
答案 0 :(得分:0)
ServletFileUpload
javadoc,无需将request
强制转换为RequestContext
,因为RequestFacade
的request
实现了HttpServletRequest
FileItem
,而是应指定类型并使用 for-each
循环:List<FileItem> items = fileUpload.parseRequest(request);
for (FileItem fileItems : items) {
if (!fileItems.isFormField()) {
File f = new File("C:\\images\\" + fileItems.getName());
fileItems.write(f);
dtoFotos.setRuta(f.getAbsolutePath());
} else {
lista.add(fileItems.getString());
}
}