How do I pass a MultipartFile from Java to Python?

schoon :

I was calling a Python program from Java, thus:

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

where fileIn was a String.

Works great, but now I need to pass a MultipartFile (ie a file, not just its name) but I do not know how to pass it to Python.

matt :

If your multipart file is the Spring class then they have some convenient methods for saving the file to disk.

import java.nio.file.Path;
import java.nio.file.Paths;
...

MultipartFile file =...;
Path tempFolder = ...;
Path tempFile = Paths.get(tempFolder.toString(), file.getName());

file.transferTo(tempFile);

//now the tempFile should have the data.
String[] commands = {"python.exe", "script.py", tempFile.toAbsolutePath().toString()};

That should create a file with the filename, and save it in the folder then start python with the file path as an argument.

To be clear, the ... are indicating code I do not know. I don't know how you created a MultipartFile, and I don't know where you want your temp folder. For testing purposes you can use Path tempFolder = Paths.get("."); or something relevant. Also I have assumed the multipart file is the spring class org.springframework.web.multipart.MultipartFile

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=123582&siteId=1