MockMultipartFile 是一个用于测试的模拟类,通常在单元测试或集成测试中模拟 MultipartFile 的行为。它属于 Spring 框架的测试包 org.springframework.mock.web 中的一部分,不应该在生产环境中使用。
因此我们采用实现MultipartFile接口类的方式,自己实现转换逻辑。
首先创建CustomMultipartFile类
具体代码如下:
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class CustomMultipartFile implements MultipartFile {
private final String name;
private final String originalFilename;
private final String contentType;
private final File file;
public CustomMultipartFile(String name, String originalFilename, String contentType, File file) {
this.name = name;
this.originalFilename = originalFilename;
this.contentType = contentType;
this.file = file;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getOriginalFilename() {
return this.originalFilename;
}
@Override
public String getContentType() {
return this.contentType;
}
@Override
public boolean isEmpty() {
return this.file.length() == 0;
}
@Override
public long getSize() {
return this.file.length();
}
@Override
public byte[] getBytes() throws IOException {
return IOUtils.toByteArray(new FileInputStream(this.file));
}
@Override
public InputStream getInputStream() throws IOException {
return new FileInputStream(this.file);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
// 可以直接使用File的transferTo方法
this.file.renameTo(dest);
}
}
在要转换处,编写方法:
public static MultipartFile convertInputStreamToFileMultipartFile(InputStream inputStream, String fileName, String contentType) throws IOException, IOException {
Path tempFilePath = Files.createTempFile("temp-", fileName);
Files.copy(inputStream, tempFilePath, StandardCopyOption.REPLACE_EXISTING);
return new CustomMultipartFile(fileName, fileName, contentType, tempFilePath.toFile());
}
核心转换逻辑伪代码
try {
BufferedInputStream bis = null;
URL url = new URL(photo_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.connect();
InputStream inputStream = conn.getInputStream();
logger.info(conn.getResponseMessage());
bis = new BufferedInputStream(inputStream);
MultipartFile multipartFile = convertInputStreamToFileMultipartFile(bis, "filename.txt", "text/plain");
}catch(Exception e) {
logger.error("文件下载/上传失败", e);
} finally {
// 清理临时文件(如果需要)
}
以上代码,灵活运用即可。