直到 Spring 5.x,我都以这种方式创建多部分文件(使用现已弃用的 CommonsMultipartFile):
OutputStream outputStream;
final DiskFileItem diskFileItem = new DiskFileItem("file", mimeType, false, fileName, fileSize, repo));
try (InputStream inputStream = new FileInputStream(actualFile)) {
outputStream = diskFileItem.getOutputStream();
IOUtils.copy(inputStream, outputStream);
return new CommonsMultipartFile(diskFileItem);
} catch (Exception e) {
throw new GoogleConversionFailedException("Cannot build MultipartFile", e);
}
如何在 Spring 6 上实现相同的结果(从 java.io.File 创建 MultipartFile)而不使用 MockMultipartFile(文档指出它应该用于测试,我真的想避免这条路线)?
您始终可以实现在您的情况下直接的接口:
public class FileMultipartFile implements MultipartFile{
private Path path;
public FileMultipartFile(Path path){
this.path=path;
}
@Override
public String getName(){
return path.getFileName().toString();
}
@Override
public String getOriginalFilename() {
return getName();
}
@Override
public String getContentType() {
try{
//not ideal as mentioned in the comments of https://stackoverflow.com/a/8973468/10871900
return Files.probeContentType(path);
}catch(IOException e){
return null;
}
}
@Override
public long getSize() {
return Files.size(path);
}
@Override
public boolean isEmpty() {
return getSize()==0;
}
@Override
public byte[] getBytes() throws IOException {
return Files.readAllBytes(path);
}
@Override
public InputStream getInputStream() throws IOException {
return Files.newInputStream(path);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
transferTo(dest.toPath());
}
@Override
public void transferTo(Path dest) throws IOException, IllegalStateException {
Files.copy(path, dest);
}
}
您可以使用
new FileMultipartFile(yourFile.toPath());
创建实例
如果您想使用自定义名称、mime 类型或类似名称,您可以添加其他字段。