使用网络文件url在java下载并返回MultipartFile
时间: 2024-04-01 10:14:47 浏览: 139
我可以为您解答这个问题。在Java中,您可以使用以下代码将网络文件下载并保存为MultipartFile:
```java
import java.io.*;
import java.net.URL;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public MultipartFile downloadFile(String fileURL) throws IOException {
URL url = new URL(fileURL);
InputStream inputStream = url.openStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
inputStream.close();
outputStream.close();
CommonsMultipartFile file = new CommonsMultipartFile();
file.setName(url.getFile().substring(url.getFile().lastIndexOf('/') + 1));
file.setBytes(imageBytes);
return file;
}
```
此方法使用CommonsMultipartFile将字节数组转换为MultipartFile,并使用输入流从URL读取数据。请确保您已添加commons-fileupload库以使用CommonsMultipartFile。希望对您有所帮助!
阅读全文