package cn.emd.platform.codegen.util;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
/**
* 文件工具
*
* @author pan
* @date 2021/3/17
*/
@Component
public class FileUtils {
/**
* 上传文件到服务器
* @param multipartFile 文件流
* @param savePath 保存路径
* @return 文件所在位置
*/
public String uploadFile(MultipartFile multipartFile,String savePath){
InputStream inputStream=null;
FileOutputStream fileOutputStream=null;
String pathname="";
try{
if(StringUtils.isEmpty(savePath)){
savePath="files/upload";
}
pathname=savePath+"/"+System.currentTimeMillis()+getSuffixName(multipartFile);
File file=new File(pathname);
//不存在路径,则创建
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
inputStream=multipartFile.getInputStream();
fileOutputStream=new FileOutputStream(file);
byte[] bytes=new byte[1024];
int len;
while ((len=inputStream.read(bytes)) !=-1){
fileOutputStream.write(bytes,0,len);
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if(inputStream !=null){
inputStream.close();
}
if(fileOutputStream !=null){
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return pathname;
}
/**
* 返回后缀名包含.
*/
public String getSuffixName(MultipartFile file){
String originalFilename = file.getOriginalFilename();
return org.apache.commons.lang3.StringUtils.isBlank(originalFilename)?
null:originalFilename.substring( originalFilename.lastIndexOf( "." ));
}
/**
* 下载文件并保存在byte[]中
* @param pathname 文件所在位置
* @return 文件字节流
* @throws FileNotFoundException
*/
public byte[] downloadFile(String pathname) throws FileNotFoundException {
File file=new File(pathname);
if(!file.exists()){
throw new FileNotFoundException(pathname);
}
ByteArrayOutputStream bos=null;
InputStream inputStream=null;
try {
bos=new ByteArrayOutputStream((int)file.length());
inputStream=new FileInputStream(pathname);
byte[] bytes=new byte[1024];
int len;
while ((len=inputStream.read(bytes)) !=-1){
bos.write(bytes,0,len);
}
return bos.toByteArray();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
bos.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}