java – 将文件转换为MultiPartFile

有没有办法将File对象转换为multipartfile?所以我可以将该对象发送给接受multipartfile接口的对象的方法
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
}

解决方法

为此存在 MockMultipartFile.如果您的代码段中的文件路径已知,则以下代码适用于我.
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);

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...