首页 > 解决方案 > 无法将 Document 转换为 MockMultipartFile

问题描述

我需要将 a 转换Document为 a MultipartFile,并且我发现我可以使用MockMultipartFile. 问题是我无法获得InputStreamMockMultipartFile 所需的内容。我正在做的是这个,我在另一个问题中发现:

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);

但是有一个问题xmlWriter.write(doc);,因为抛出异常说:

Invalid object: [#document: null]

我看过这个答案,但我的 XML 不是计算机上的文件,它是我从数据库中读取的字符串,我转换为 XML。

我也试过这个:

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

new OutputFormat已弃用。

标签: javaxmlspringmultipart

解决方案


推荐阅读