2013-05-03 3 views
0

Я делаю приложение, которое может конвертировать загруженный файл в xml-файл. Загруженный файл - это файл xls. Я превратил xls-конвертер в xml с apache-poi. Я также добавил функции загрузки и загрузки. Когда файл xls загружается, он должен быть преобразован в xml контроллером и сохраняется в базе данных (Mysql), но он не работает. приложение возвращает исключение:конвертировать загруженный файл (xls) в xml

java.lang.ClassCastException: org.springframework.web.multipart.commons.CommonsMultipartFile cannot be cast to java.io.InputStream 

И это контроллер:

@Controller 
public class FileController { 

@Autowired 
private FileDAO documentDao; 

@RequestMapping("/index") 
public String showDocument(Map<String, Object> map) { 
    try { 
     map.put("document", new File()); 
     map.put("documentList", documentDao.list()); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return "documents"; 
} 

@SuppressWarnings("deprecation") 
@RequestMapping(value = "/save", method = RequestMethod.POST) 
public String save(@ModelAttribute("document") File document, 
     @RequestParam("file") MultipartFile file) throws IOException { 

    System.out.println("Name:" + document.getName()); 
    System.out.println("Desc:" + document.getDescription()); 
    System.out.println("File:" + file.getName()); 
    System.out.println("ContentType:" + file.getContentType()); 

    /* 
    * start to convert xls to xml 
    * */ 
    try { 
     InputStream input = (InputStream) file; 
     HSSFWorkbook workbook = new HSSFWorkbook(input); 
     HSSFSheet spreadsheet = workbook.getSheetAt(0); 

     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document doc = builder.newDocument(); 
     doc.setXmlStandalone(true); 

     Element spectraexchange = doc.createElementNS("http://www.lstelcom.com/Schema/SPECTRAexchange", "SPECTRAEXCHANGE"); 
     spectraexchange.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); 
     spectraexchange.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); 
     spectraexchange.setAttribute("version", "2.4.28"); 
     doc.appendChild(spectraexchange); 

     for(int i=1; i<=2; i++){ 

      HSSFRow row = spreadsheet.getRow(i); 

      Element application = doc.createElement("APPLICATION"); 
      spectraexchange.appendChild(application); 

      Element svid = doc.createElement("SV_SV_ID"); 
      application.appendChild(svid); 
      svid.appendChild(doc.createTextNode("12")); 

      Element ssid = doc.createElement("SS_SS_ID"); 
      application.appendChild(ssid); 
      ssid.appendChild(doc.createTextNode("140")); 

      Element address = doc.createElement("ADDRESS");//men-generate <ADDRESS> 
      application.appendChild(address);//men-generate </ADDRESS> 
      address.setAttribute("AD_TYPE", "L"); 

      Element adspplus = doc.createElement("AD_SPPLUS_TYPE");//men-generate <AD_SPPLUS_TYPE> 
      address.appendChild(adspplus);//men-generate </AD_SPPLUS_TYPE> 
      adspplus.appendChild(doc.createTextNode("L"));//<AD_SPPLUS_TYPE>L<AD_SPPLUS_TYPE> 

      try { 
       Element adcompany = doc.createElement("AD_COMPANY"); 
       address.appendChild(adcompany); 
       adcompany.appendChild(doc.createTextNode(row.getCell((short) 33).getStringCellValue())); 
       if(row.getCell((short) 33).getStringCellValue()==null){ 
        continue; 
       } 
      } catch (Exception e) { 
       e.getMessage(); 
      } 

      try { 
       Element adstreet = doc.createElement("AD_STREET"); 
       address.appendChild(adstreet); 
       adstreet.appendChild(doc.createTextNode(row.getCell((short) 35).getStringCellValue())); 
       if(row.getCell((short) 35).getStringCellValue()==null){ 
        continue; 
       } 
      } catch (Exception e) { 
       e.getMessage(); 
      } 


      Element adcountry = doc.createElement("AD_COUNTRY"); 
      address.appendChild(adcountry); 
      adcountry.appendChild(doc.createTextNode("INS")); 

      try { 
       Element adcity = doc.createElement("AD_CITY"); 
       address.appendChild(adcity); 
       adcity.appendChild(doc.createTextNode(row.getCell((short) 36).getStringCellValue())); 
       if(row.getCell((short) 36).getStringCellValue()==null) { 
        continue; 
       } 
      } catch (Exception e) { 
       e.getMessage(); 
      } 

      Element station = doc.createElement("STATION"); 
      application.appendChild(station); 

      Element transmitter = doc.createElement("TRANSMITTER"); 
      station.appendChild(transmitter); 

      try { 
       Element eqpname = doc.createElement("EQP_EQUIP_NAME"); 
       transmitter.appendChild(eqpname); 
       eqpname.appendChild(doc.createTextNode(row.getCell((short) 2).getStringCellValue())); 
       if(row.getCell((short) 2).getStringCellValue()==null){ 
        continue; 
       } 
      } catch (Exception e) { 
       e.getMessage(); 
      } 


      Element eqptype = doc.createElement("EQP_TYPE_IS_APPROVED"); 
      transmitter.appendChild(eqptype); 
      eqptype.appendChild(doc.createTextNode("1")); 

      try { 
       Element eqpmodel = doc.createElement("EQP_EQUIP_MODEL"); 
       transmitter.appendChild(eqpmodel); 
       eqpmodel.appendChild(doc.createTextNode(row.getCell((short) 4).getStringCellValue())); 
       if(row.getCell((short) 4).getStringCellValue()==null){ 
        continue; 
       } 

      } catch (Exception e) { 
       e.getMessage(); 
      } 

      try { 
       Element eqpprod = doc.createElement("EQP_EQUIP_PROD"); 
       transmitter.appendChild(eqpprod); 
       eqpprod.appendChild(doc.createTextNode(row.getCell((short) 6).getStringCellValue())); 
       if(row.getCell((short) 6).getStringCellValue()==null){ 
        continue; 
       } 
      } catch (Exception e) { 
       e.getMessage(); 
      } 


     } 

     TransformerFactory tfactory = TransformerFactory.newInstance(); 
     Transformer transformer = tfactory.newTransformer(); 
     transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
     transformer.setOutputProperty("{http:/xml.apache.org/xslt}indent-amount", "2"); 
     transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); 

     DOMSource source = new DOMSource(doc); 
     StreamResult result = new StreamResult(System.out); 
     //StreamResult result = new StreamResult("E://XlsToXml/standard_query02.xml"); 
     transformer.transform(source, result); 
     /* 
     * end of convertion 
     * */ 

     //----------------------------------// 
     Blob blob = Hibernate.createBlob(((MultipartFile) doc).getInputStream()); 

     document.setFilename(((MultipartFile) doc).getOriginalFilename()); 
     document.setContent(blob); 
     document.setContentType(((MultipartFile) doc).getContentType()); 

     documentDao.save(document); 

    }catch (IOException e) { 
     System.out.println("IOException " + e.getMessage()); 
    } catch (ParserConfigurationException e) { 
     System.out.println("ParserConfigurationException " + e.getMessage()); 
    } catch (TransformerConfigurationException e) { 
     System.out.println("TransformerConfigurationException "+ e.getMessage()); 
    } catch (TransformerException e) { 
     System.out.println("TransformerException " + e.getMessage()); 
    }catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return "redirect:/index.html"; 
} 

@RequestMapping("/download/{documentId}") 
public String download(@PathVariable("documentId") Integer documentId, 
     HttpServletResponse response) { 

    File doc = documentDao.get(documentId); 

    try { 
     response.setHeader("Content-Disposition", "inline;filename=\"" 
       + doc.getFilename() + "\""); 
     OutputStream out = response.getOutputStream(); 
     response.setContentType(doc.getContentType()); 
     IOUtils.copy(doc.getContent().getBinaryStream(), out); 
     out.flush(); 
     out.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } 

    return null; 
} 

@RequestMapping("/remove/{documentId}") 
public String remove(@PathVariable("documentId") Integer documentId) { 

    documentDao.remove(documentId); 

    return "redirect:/index.html"; 
} 

} 

Может быть, есть что-то я должен сделать с контроллером. Любые идеи, решения или предложения очень приветствуются и оцениваются.

С наилучшими пожеланиями,

Юнус

ответ

2

Я думаю, что это линия дает эту ошибку.

InputStream input = (InputStream) file; 

Вы не можете бросить MultipartFile объект file непосредственно InputStream. Вы должны использовать метод getInputStream() из MultipartFile, как это: -

InputStream input = file.getInputStream(); 
+0

это работает. Теперь контроллер может получить файл и сможет преобразовать файл в xml. Но приложение возвращает новое исключение: 'java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DocumentImpl не может быть передан в org.springframework.web.multipart.MultipartFile' и файл не может быть сохранен в базе данных. любая идея или предложение? – yunus

+0

Рад помочь вам! :) – SudoRahul

Смежные вопросы