文件上传完整工具类
如果你在我发布的文件上传的博客没有看懂,这是完整的工具类,你记得把xml文件添加完整了就好。
package com.wb.srpingboot.demoz.utils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;
import org.xeustechnologies.jtar.TarEntry;
import org.xeustechnologies.jtar.TarOutputStream;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.*;
/**文件上传工具类
* @author 阿萨
*/
public class UploadFiles {
/**UPLOAD_URL 带压缩的文件目录和文件上传路径*/
public static String UPLOAD_URL;
/**文件的访问路径(基于外置的tomcat图床)*/
public static String DOWNLOAD_URL;
/**指定打成的tar包的名称和tar包存放的位置*/
public static String TAR_FILE_PATH;
/**
*文件的虚拟访问路径(直接访问本地的文件)
*/
public static String STATIC_ACCESS_PATH;
/*private static Date data = new Date();
private static SimpleDateFormat adf = new SimpleDateFormat("MM-dd");
private static String format = adf.format(data);*/
// 读取yml里的属性值
static {
YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
//可以加载多个yml文件
yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
Properties properties = yamlMapFactoryBean.getObject();
//获取yml里的路径参数
if (properties != null) {
UPLOAD_URL = properties.getProperty("upload-url");
DOWNLOAD_URL = properties.getProperty("download-url");
TAR_FILE_PATH = properties.getProperty("tarFilePath");
STATIC_ACCESS_PATH = properties.getProperty("uploadFile.staticAccessPath");
if (UPLOAD_URL == null || "".equals(UPLOAD_URL)){
throw new RuntimeException("上传路径为空");
}
if (DOWNLOAD_URL == null || "".equals(DOWNLOAD_URL)){
throw new RuntimeException("访问路径为空");
}
if (TAR_FILE_PATH == null || "".equals(TAR_FILE_PATH)){
throw new RuntimeException("压缩路径为空");
}
if (STATIC_ACCESS_PATH == null || "".equals(STATIC_ACCESS_PATH)){
throw new RuntimeException("文件的访问虚拟路径为空");
}
}else {
throw new RuntimeException("找不到名为application.yml配置文件");
}
//上传路径
File targetFile = new File(UPLOAD_URL);
//如果路径不存在就创建
if (!targetFile.exists()) {
targetFile.mkdirs();
}
}
/**
* TODO: 文件上传(可一次上传多个文件也可以一次上传一个文件)
* @param files 上传的文件
* @return com.wb.srpingboot.demoz.utils.Result
*/
public static Result uploads(MultipartFile[] files){
if(files.length > 0 && !(files[0].isEmpty())){
//创建流
FileInputStream fis = null;
FileOutputStream fos = null;
//创建通道
FileChannel inChannel = null;
FileChannel outChannel = null;
String newName;
List<String> imgName = new ArrayList<>();
try {
for (MultipartFile file : files) {
String realName = file.getOriginalFilename();
//初始化文件新名字
if (realName != null && realName != "") {
//获取文件后缀
String suffixName = realName.substring(realName.lastIndexOf("."));
//生成新名字
newName = UUID.randomUUID().toString().replaceAll("-", "") + suffixName;
} else {
return Result.fail("文件名不可为空");
}
fis = (FileInputStream) file.getInputStream();
//开始上传
fos = new FileOutputStream(UPLOAD_URL + "\\" + newName);
//通道间传输
inChannel = fis.getChannel();
outChannel = fos.getChannel();
//上传
inChannel.transferTo(0, inChannel.size(), outChannel);
imgName.add(newName);
}
//打成压缩包
//toCompress("haha");
}catch (IOException e) {
return Result.fail("文件上传路径错误");
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭资源
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return Result.ok(imgName);
}
return Result.fail("请选择文件");
}
/**
* 文件上传方法(单个)
*/
public static Result uploading(MultipartFile file) {
//获取文件名
String realName = file.getOriginalFilename();
String newName = null;
if(realName != null && realName != ""){
//获取文件后缀
String suffixName = realName.substring(realName.lastIndexOf("."));
//生成新名字
newName = UUID.randomUUID().toString().replaceAll("-", "")+suffixName;
}else {
return Result.fail("文件名不可为空");
}
//创建流
FileInputStream fis = null;
FileOutputStream fos = null;
//创建通道
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
fis = (FileInputStream)file.getInputStream();
//开始上传
fos = new FileOutputStream(UPLOAD_URL+"\\"+newName);
//通道间传输
inChannel = fis.getChannel();
outChannel = fos.getChannel();
//上传
inChannel.transferTo(0,inChannel.size(),outChannel);
}catch (IOException e){
return Result.fail("文件上传路径错误");
}finally {
//关闭资源
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return Result.ok(newName);
}
/**
* TODO: 打成压缩包
* UPLOAD_URL 带压缩的文件目录
* TAR_FILE_PATH 指定打成的tar包的名称和tar包存放的位置
* @param name 压缩的文件名
*/
private static void toCompress(String name){
FileOutputStream dest = null;
TarOutputStream tarOut = null;
try {
//设置tar包位置
dest = new FileOutputStream(TAR_FILE_PATH + name + ".tar");
tarOut = new TarOutputStream(new BufferedOutputStream(dest));
//设置待打包源文件的位置
File sourceFile = new File(UPLOAD_URL);
//listFiles是获取该目录下所有文件和目录的绝对路径
File[] sourceFiles = sourceFile.listFiles();
if (sourceFiles != null) {
for (File f : sourceFiles) {
tarOut.putNextEntry(new TarEntry(f, f.getName()));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
int count;
byte[] data = new byte[2048];
//将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此缓冲的输出流。
//public void write(byte[] b,int off,int len);
//从此字节输入流中给定偏移量处开始将各字节读取到指定的 byte 数组中。
//public int read(byte[] b,int off,int len);
while ((count = bis.read(data)) != -1) {
// write(byte[] wBuf, int wOffset, int numToWrite)
// 将字节写入当前的tar存档条目。
tarOut.write(data, 0, count);
}
tarOut.flush();
bis.close();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (tarOut != null){
tarOut.close();
}
if (dest != null){
dest.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
配置文件里写的
# 配置文件访问路径
uploadFile:
# 文件本地路径
path: D:/img/
# 文件访问虚拟路径
staticAccessPath: /upload/**
# 配置图片访问路径
upload-url: D:/img/
# 基于外置tomcat的访问路径
download-url: http://192.168.31.53:8081/img/
# 压缩文件存放路径
tarFilePath: D:/test/
感谢观看。