本地文件File类型转换成multipartFile类型(groovy)

在使用groovy的时候,遇到要将本地文件添加到附件中的问题,经过一番测试,最终使用了

def  file = new File (本地文件路径和名称)

def input = new FileInputStream(file)

def multipartFile = new  MockMultipartFile(文件名,文件名,"text/pain",input)

其中,因为multipartFile是接口,要将file转换成此类型的话,必须使用它的实现类.

希望此方法能够帮助大家

但是此方法最好只用在开发环境下,生产环境是没办法使用的.

替代的办法如下:

File file = new File("/path/to/file");
FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());

try {
    InputStream input = new FileInputStream(file);
    OutputStream os = fileItem.getOutputStream();
    IOUtils.copy(input, os);
    // Or faster..
    // IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());
} catch (IOException ex) {
    // do something.
}

MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

猜你喜欢

转载自blog.csdn.net/weixin_42228950/article/details/82993686
今日推荐