byte数组与MultipartFile的相互转化
时间: 2023-11-11 10:00:13 浏览: 188
将byte数组转化为MultipartFile可以通过实现自定义的MultipartFile类来实现,代码如下:
```java
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
public class ByteToMultipartFile implements MultipartFile {
private final byte[] fileContent;
private final String fileName;
public ByteToMultipartFile(byte[] fileContent, String fileName) {
this.fileContent = fileContent;
this.fileName = fileName;
}
@Override
public String getName() {
return null;
}
@Override
public String getOriginalFilename() {
return fileName;
}
@Override
public String getContentType() {
return "application/octet-stream";
}
@Override
public boolean isEmpty() {
return fileContent == null || fileContent.length == 0;
}
@Override
public long getSize() {
return fileContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return fileContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(fileContent);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
new FileOutputStream(dest).write(fileContent);
}
}
```
将MultipartFile转化为byte数组可以通过以下代码实现:
```java
public byte[] multipartFileToByteArray(MultipartFile file) throws IOException {
return file.getBytes();
}
```
阅读全文