File如何转换成MultipartFile
MutipartFile是spring里面定义的接口,它封装了用户在上传图片时所包含的所有信息,但是有些时候我们要将file转换成MutipartFile,才能在保持原有代码逻辑的情况下方便代码的调整,但是file不能直接转换成MutipartFile,现在就要教大家如何将file转换成MutipartFile。
如果要转换,要用到的包是spring-test
maven:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.2.5.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> </dependencies>
或者
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.2.5.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> </dependencies>
maven配置好了之后,要用到一个非常重要的类MockMultipartFile
他是继承MultipartFile接口来模拟MultipartFile。当然具体的实现要自己看源码,我们要讲的是如何file转换成MultipartFile。
转换的方式很简单,就是创建MockMultipartFile的构造函数。
具体的有四个构造函数
-MockMultipartFile(String name, byte[] content)
-MockMultipartFile(String name, InputStream contentStream)
-MockMultipartFile(String name, String originalFilename, String contentType, byte[] content)
-MockMultipartFile(String name, String originalFilename, String contentType, InputStream contentStream)
*name文件名
*originalFilename原文件名
*contentStream输入流
*content byte数组
例子:
MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
下面贴上我在应用上面的截取的具体代码片段:
要求:把url里的图片导入到本地。
WebFileUtils.java
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.springframework.stereotype.Service;
@Service("webFileUtils")
public class WebFileUtils {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(WebFileUtils.class);
/**
* 根据url拿取file
*
* @param url
* @param suffix
* 文件后缀名
* */
public static File createFileByUrl(String url, String suffix) {
byte[] byteFile = getImageFromNetByUrl(url);
if (byteFile != null) {
File file = getFileFromBytes(byteFile, suffix);
return file;
} else {
logger.info("生成文件失败!");
return null;
}
}
/**
* 根据地址获得数据的字节流
*
* @param strUrl
* 网络连接地址
* @return
*/
private static byte[] getImageFromNetByUrl(String strUrl) {
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
return btImg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从输入流中获取数据
*
* @param inStream
* 输入流
* @return
* @throws Exception
*/
private static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
// 创建临时文件
private static File getFileFromBytes(byte[] b, String suffix) {
BufferedOutputStream stream = null;
File file = null;
try {
file = File.createTempFile("pattern", "." + suffix);
System.out.println("临时文件位置:"+file.getCanonicalPath());
FileOutputStream fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(b);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
public static void main(String[] args) {
WebFileUtils.createFileByUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508327007250&di=b7be3e44999983ec75ba54537287ff13&imgtype=0&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Faa64034f78f0f736ce4ff5720055b319ebc4130b.jpg","jpg");
}
}
ImgUploadServiceImpl.java
public MultipartFile createImg(String url){
try {
// File转换成MutipartFile
File file = WebFileUtils.createFileByUrl(url, "jpg");
FileInputStream inputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
//注意这里面填啥,MultipartFile里面对应的参数就有啥,比如我只填了name,则
//MultipartFile.getName()只能拿到name参数,但是originalFilename是空。
return multipartFile;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
以上是我做项目中对file转MultipartFile的分享。