HttpServletRequest无法强制转换为MultipartHttpServletRequest

时间:2014-05-13 07:03:36

标签: java spring jsp spring-mvc

我正在尝试上传Excel文件并在控制台中打印每个单元格的内容。这是我的代码..

JSP:

                <c:url value="/my-account/readExcel" var="readExcel" />
                <form:form action="${readExcel}" method="post" commandName="excelFileUploadForm" enctype="multipart/form-data">
                   <form:input id="fineName" path="fileName" type="file" />
                   <input type="submit" value="Uplaod" />
                </form:form>

ExcelFileUploadForm:

 public class ExcelFileUploadForm
 {
  private MultipartFile fileName;

   public MultipartFile getFileName()
   {
    return fileName;
    }

   public void setFileName(final MultipartFile fileName)
   {
    this.fileName = fileName;
    }
}

控制器:

@RequestMapping(value = "/readExcel", method = RequestMethod.POST)
@RequireHardLogIn
public String readExcel(final HttpServletRequest request, final HttpServletResponse response) throws CMSItemNotFoundException,
        IOException
{
    final MultipartHttpServletRequest mpr = (MultipartHttpServletRequest) request;
    final CommonsMultipartFile file = (CommonsMultipartFile) mpr.getFile("fileName");
    read(file);
    return "redirect:/my-account";
}

public void read(final CommonsMultipartFile inputFile) throws IOException
{
    Workbook w;
    try
    {
        w = Workbook.getWorkbook(inputFile.getInputStream());
        // Get the first sheet
        final Sheet sheet = w.getSheet(0);
        // Loop over first 10 column and lines

        for (int j = 0; j < sheet.getColumns(); j++)
        {
            for (int i = 0; i < sheet.getRows(); i++)
            {
                final Cell cell = sheet.getCell(j, i);
                final CellType type = cell.getType();
                if (type == CellType.LABEL)
                {
                    System.out.println("I got a label " + cell.getContents());
                }

                if (type == CellType.NUMBER)
                {
                    System.out.println("I got a number " + cell.getContents());
                }

            }
        }
    }
    catch (final BiffException e)
    {
        e.printStackTrace();
    }
}

当我通过浏览按钮上传文件并点击上传时。它给出了Casting错误

HTTP Status 500 - Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest

我无法弄清楚我做错了什么。请帮忙。

1 个答案:

答案 0 :(得分:1)

请在弹簧配置(app config)中添加Multipart Resolver,如下所示:

<bean id="multiPartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>