inputstream转为multipartfile
时间: 2023-08-04 09:09:51 浏览: 123
要将InputStream转换为MultipartFile,您可以使用Commons FileUpload库来实现。以下是一个示例代码:
```java
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public MultipartFile convertToMultipartFile(InputStream inputStream, String filename) throws IOException {
File tempFile = File.createTempFile("temp", null);
try (InputStream in = inputStream) {
Files.copy(in, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
DiskFileItem fileItem = new DiskFileItem("file", Files.probeContentType(tempFile.toPath()), false, tempFile.getName(), (int) tempFile.length(), tempFile.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
return multipartFile;
}
```
您可以通过将InputStream传递给`convertToMultipartFile`方法来将其转换为MultipartFile。请确保在使用完MultipartFile后删除临时文件。
阅读全文