java 图片地址转MultipartFile对象
时间: 2023-11-24 10:52:40 浏览: 147
以下是Java将图片地址转换为MultipartFile对象的代码示例:
```java
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageUtil {
/**
* 将网络图片地址转换为MultipartFile对象
*
* @param imgUrl 图片地址
* @return MultipartFile对象
*/
public static MultipartFile getMultipartFile(String imgUrl) throws IOException {
URL url = new URL(imgUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
byte[] bytes = outputStream.toByteArray();
outputStream.close();
// 将字节数组转换为MultipartFile对象
MultipartFile multipartFile = new MockMultipartFile("file", "img.jpg", "image/jpeg", bytes);
return multipartFile;
}
}
```
该代码使用了Spring框架中的MockMultipartFile类,将字节数组转换为MultipartFile对象。在方法中,我们首先通过图片地址获取图片的输入流,然后将输入流转换为字节数组,最后将字节数组转换为MultipartFile对象。
阅读全文