Java – convert file to multipartfile

Is there any way to convert a file object to a multipart file? So can I send this object to the method of the object that accepts the multipartfile interface?

File myFile = new File("/path/to/the/file.txt")

multipartfile ....?

def (multipartfile file) {
  def is = new BufferedInputStream(file.getInputStream())
  //do something interesting with the stream
}

Solution

There is a mockmultipartfile for this If the file path in your code snippet is known, the following code applies to me

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.Mockmultipartfile;

Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
    content = Files.readAllBytes(path);
} catch (final IOException e) {
}
multipartfile result = new Mockmultipartfile(name,originalFileName,contentType,content);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>