当前位置: 代码迷 >> Java Web开发 >> 资料上传时的类型转换
  详细解决方案

资料上传时的类型转换

热度:1580   发布时间:2013-02-25 21:17:27.0
文件上传时的类型转换
本人在学习李腾飞的CMS视频,在进行文章附件上传时遇到了问题:
Java code
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // 获取参数值        Article article = new Article();        try {            article = (Article) RequestUtil.copyParams(Article.class, request);        } catch (InvocationTargetException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        // 从request中获得上传文件的有关信息        Attachment[] attachments = (Attachment[]) request.getParameterMap().get("attachs");        if (attachments != null) {            for (Attachment atta : attachments) {                System.out.println((atta).getName() + ",已经被上传,文件类型是:" + (atta).getContentType());            }        }        article.setCreatetime(new Date());        articleDao.addArticle(article);        request.getRequestDispatcher("add_article_success.jsp").forward(request, response);    }



下面这一句给出的错误提示是:不能进行类型转换 Cannot cast from String[] to Attachment[]

Java code
Attachment[] attachments = (Attachment[]) request.getParameterMap().get("attachs");


因为我都是按照视频上讲的一步一操作的,我实在不知道哪里出了问题

请各位给指点一下



------解决方案--------------------------------------------------------
打印request.getParameterMap().get("attachs");来看是什么

------解决方案--------------------------------------------------------
request.getParameterMap().get("attachs");获得的是Object类型的数据,你要强转成数组类型当然会报错啊。。
------解决方案--------------------------------------------------------
用spring mvc 或者struts 框架上传文件。 很简单呀。
------解决方案--------------------------------------------------------
request.getParameterMap().get("attachs");
你前台给的数据map中名为attachs的值不是Attachment数组,而是String数组,当然转不了啦
  相关解决方案