如何将MultipartFile从Java传递到Python?

前端之家收集整理的这篇文章主要介绍了如何将MultipartFile从Java传递到Python? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我从Java调用Python程序,因此:

  1. String[] command = {"python.exe","script.py",fileIn};
  2. ProcessBuilder probuilder = new ProcessBuilder(command);
  3. Process process = probuilder.start();
  4. BufferedReader bfr = new BufferedReader(new InputStreamReader(process.getInputStream()));

其中fileIn是一个字符串.

效果很好,但是现在我需要传递MultipartFile(即文件,而不仅仅是其名称),但是我不知道如何将其传递给Python.

最佳答案
如果您的多部分文件是Spring类,则它们有一些方便的方法可以将文件保存到磁盘.

  1. import java.nio.file.Path;
  2. import java.nio.file.Paths;
  3. ...
  4. MultipartFile file =...;
  5. Path tempFolder = ...;
  6. Path tempFile = Paths.get(tempFolder.toString(),file.getName());
  7. file.transferTo(tempFile);
  8. //now the tempFile should have the data.
  9. String[] commands = {"python.exe",tempFile.toAbsolutePath().toString()};

那应该创建一个带有文件名的文件,并将其保存在文件夹中,然后以文件路径作为参数启动python.

需要明确的是,…表示我不知道的代码.我不知道您如何创建MultipartFile,也不知道您的临时文件夹在哪里.为了进行测试,可以使用Path tempFolder = Paths.get(“.”);或相关的东西.我也假设这个多部分文件是spring class org.springframework.web.multipart.MultipartFile

猜你在找的Java相关文章