InputStream 转 MultipartFile
时间: 2023-10-13 09:23:10 浏览: 202
将 `InputStream` 转换为 `MultipartFile` 可以通过创建一个自定义的 `MultipartFile` 实现。以下是一个示例代码:
```java
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class InputStreamMultipartFile implements MultipartFile {
private final String name;
private final String originalFileName;
private final String contentType;
private final byte[] content;
public InputStreamMultipartFile(String name, String originalFileName, String contentType, byte[] content) {
this.name = name;
this.originalFileName = originalFileName;
this.contentType = contentType;
this.content = content;
}
@Override
public String getName() {
return name;
}
@Override
public String getOriginalFilename() {
return originalFileName;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public boolean isEmpty() {
return content == null || content.length == 0;
}
@Override
public long getSize() {
return content.length;
}
@Override
public byte[] getBytes() throws IOException {
return content;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(content);
}
@Override
public void transferTo(java.io.File file) throws IOException, IllegalStateException {
throw new UnsupportedOperationException("Not implemented");
}
}
```
然后,您可以使用以下代码将 `InputStream` 转换为 `MultipartFile`:
```java
InputStream inputStream = ...;
MultipartFile multipartFile = new InputStreamMultipartFile("file", "filename.txt", "text/plain", inputStream.readAllBytes());
```
请注意,上述示例中的 `transferTo` 方法未实现。如果需要支持此方法,您可以在自定义 `MultipartFile` 类中实现该方法。
阅读全文