将图像加载到 Java 数据库时出错

时间:2021-07-25 13:47:25

标签: java image web

为什么在尝试将图像加载到 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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

  1. 根据ServletFileUpload javadoc,无需将request 强制转换为RequestContext,因为RequestFacaderequest 实现了HttpServletRequest
  2. 此外,无需将文件项强制转换为 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());
    }
}