0

I need to convert a Document to a MultipartFile, and I've found I can use MockMultipartFile. The problem is that I can't get the InputStream that I need for my MockMultipartFile. What I'm doing is this, that I've found in another question:

Document doc = XmlUtilities.stringToXml(xml);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    XMLWriter xmlWriter;
    try {
        xmlWriter = new XMLWriter(outputStream, OutputFormat.createPrettyPrint());
        xmlWriter.write(doc);
        xmlWriter.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

        MultipartFile mpfile = new MockMultipartFile(functionalityName, functionalityName, "text/xml", inputStream);

But there is a problem in xmlWriter.write(doc);, because the exeption is thrown saying:

Invalid object: [#document: null]

I've had a look at this answer, but my XML is not a File on the computer, it's a String that I read from DB that I convert to XML.

I've also tried this:

 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  OutputFormat outputFormat = new OutputFormat(document);
  XMLSerializer serializer = new XMLSerializer(outputStream, outputFormat);
  serializer.serialize(document);
  return new ByteArrayInputStream(outputStream.toByteArray());

But new OutputFormat is deprecated.

Usr
  • 2,628
  • 10
  • 51
  • 91
  • All you need to do is convert your content from database to a byte array. Then MockMultipartFile will happily take it. I assume "xml" that you're obtaining from database is a String. All you need to do to convert it to bytes is the getBytes() method with the correct encoding, which will usually be UTF-8. So, `byte[] bytes = xml.getBytes(StandardCharsets.UTF_8);` – kumesana Apr 24 '19 at 09:40
  • Hi @kumesana, thank you for the tip. How do I know if my MultipartFile is correct? Because I'm passing it to another function and it doesn't behave as I need, so I'm trying to understand in which part is the error. Also, the MockMultipartFile constructor wants the name of the file. I'm passing a random string right now, but is it correct? What does it use it for? – Usr Apr 24 '19 at 09:51
  • 1
    I guess check name, filename, content type, and content. A MultipartFile is about providing these infos. As for the name, beware. MockMultipartFile's doc is misleading. There are two things: the name of the field and the name of the file. The name of the field needs to be something specific: *Multi* of multipart implies that there will be more than one, and there you're supposed to wonder which part will you pick for which task. The answer will be: by their names. Beside field name, there is the possibility to specify a filename, but you don't have to. It's in case you'd need one. – kumesana Apr 24 '19 at 10:15
  • Thank you @kumesana . If you add an answer I'll accept it :) – Usr Apr 24 '19 at 10:42

0 Answers0