Reputation: 1595
I am trying to write a service that receives a xml file and parses it and does some additional processing. At the UI controller I converted the multipart file contents to a string and passed it to the service. From the UI controller - I upload the file and call the service method to parse the xml file
MultipartFile newFile=multiPartRequest.getFile("newFileUpload");
String fileContent = new String(newFile.getBytes());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(fileContent));
doc = dBuilder.parse(is);
However, doc is always null. What is the best way for me to rest this xml file?
Upvotes: 0
Views: 3830
Reputation: 999
I think its a problem with the
String fileContent String fileContent = new String(newFile.getBytes());
Since not all the bytes of the file are just text , you have the header and eof and bytes that don't represent a text .
What you should do is make a InputStream and build the document off that , like so :
try{
MultipartFile newFile=multiPartRequest.getFile("newFileUpload");
InputStream is = new newFile.getInputStream();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
} catch (SAXException | IOException | ParserConfigurationException ex) {
Logger.getLogger(JavaApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
Upvotes: 2