import org.apache.commons.io.FileUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
public class UrlToMultipartFileUtil {
/**
* description 网络TRL中下载图片
*
* @param uri
* @param folder 存放文件的文件夹
* @return java.lang.String
*/
private String downloadByUrl(String uri, String folder) {
ReadableByteChannel readableByteChannel = null;
FileChannel fileChannel = null;
File file;
URL url;
FileOutputStream fileOutputStream = null;
try {
url = new URL(uri);
//首先从 URL stream 中创建一个 ReadableByteChannel 来读取网络文件
readableByteChannel = Channels.newChannel(url.openStream());
String fileName = System.currentTimeMillis() + url.getPath().substring(url.getPath().lastIndexOf("."));
String path = folder + "/" + fileName;
file = new File(path);
if (!file.getParentFile().exists() && !file.getParentFile().isDirectory()) {
file.getParentFile().mkdirs();
}
//通过 ReadableByteChannel 读取到的字节会流动到一个 FileChannel 中,然后再关联一个本地文件进行下载操作
fileOutputStream = new FileOutputStream(file);
fileChannel = fileOutputStream.getChannel();
//最后用 transferFrom()方法就可以把 ReadableByteChannel 获取到的字节写入本地文件
fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
return fileName;
} catch (Exception e) {
e.printStackTrace();
return "";
} finally {
try {
if (null != readableByteChannel) {
readableByteChannel.close();
}
if (null != fileChannel) {
fileChannel.close();
}
if (null != fileOutputStream) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param
* @return
* @author:liuyu
* @功能说明:File转MultipartFile
*/
private static MultipartFile fileToMultipartFile(File file) throws Exception {
InputStream inputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
return multipartFile;
}
//通过url将文件下载到本地
public static int downloadFileFromUrl(String url, String localFilePath) {
try {
URL httpUrl = new URL(url);
File f = new File(localFilePath);
FileUtils.copyURLToFile(httpUrl, f);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
}
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
</dependency>