在工具类编写导入方法
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.channels.FileChannel;
public class FileUtil extends org.apache.commons.io.FileUtils{
public static boolean writeMultipartFile(MultipartFile file, String descFileName){
File descFile = new File(descFileName);
File tmpFile = null;
FileInputStream fi = null;
FileOutputStream fo = null;
FileChannel in = null;
FileChannel out = null;
try {
if (descFile.exists()==false) {//判断文件目录的存在
File filemkd=new File(descFile.getParent());
filemkd.mkdirs();
}
tmpFile = new File(descFile.getParent(), "tmp.tmp");
InputStream fin = file.getInputStream();
if(fin instanceof FileInputStream){
fi = (FileInputStream)fin;
} else if(fin instanceof ByteArrayInputStream) {
FileOutputStream fo_tmp = new FileOutputStream(tmpFile);
int t = 0;
while((t = fin.read()) != -1)
fo_tmp.write(t);
fo_tmp.flush();
fo_tmp.close();
fi = new FileInputStream(tmpFile);
}
fo = new FileOutputStream(descFile);
in = fi.getChannel();//得到对应的文件通道
out = fo.getChannel();//得到对应的文件通道
in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
fi.close();
in.close();
fo.close();
out.close();
if(tmpFile.exists()) {
tmpFile.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
}
controller层调用
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
String realpath = System.getProperty("user.dir") + File.separator + "upload";
File uploadFile = new File(realpath);
//判断根目录是否存在该文件夹document
if (!uploadFile.exists() && !uploadFile.isDirectory()){
uploadFile.mkdirs();
}
String currDate = CommonMethod.getCurrentMonth();
String filename = currDate.substring(0, 4) + File.separator + currDate.substring(5, 7)
+ File.separator + MD5.getMD5(file.getOriginalFilename() + System.currentTimeMillis()) + file.getOriginalFilename();
String filePath = realpath + File.separator + filename;
String fileParam = "upload" + File.separator + filename;
if (!FileUtil.writeMultipartFile(file,filePath)) {
return "导入失败!";
}
return "导入成功!";
}
MD5为加密方法
public class MD5{
public static String getMD5(String par){
if (par == null || par.trim().isEmpty()){
return "";
}
byte[] source;
try {
source = par.getBytes("utf-8");
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException("MD5加密出错!");
}
String s = null;
// 用来将字节转换成 16 进制表示的字符
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try{
java.security.MessageDigest md = java.security.MessageDigest.getInstance( "MD5" );
md.update(source);
byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数,
// 用字节表示就是 16 个字节
char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,
// 所以表示成 16 进制需要 32 个字符
int k = 0; // 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++){ // 从第一个字节开始,对 MD5 的每一个字节
// 转换成 16 进制字符的转换
byte byte0 = tmp[i]; // 取第 i 个字节
str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
// >>> 为逻辑右移,将符号位一起右移
str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
}
s = new String(str); // 换后的结果转换为字符串
}
catch (Exception e){
e.printStackTrace();
}
return s;
}
}
SpringBoot项目会默认MultipartFile文件上传最大为1MB,可通过ICO容器管理设置
@Configuration
public class FileUploadConfiuration {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件大小200mb
factory.setMaxFileSize(DataSize.ofMegabytes(200L));
//设置总上传数据大小10GB
factory.setMaxRequestSize(DataSize.ofGigabytes(10L));
return factory.createMultipartConfig();
}
}
下载文件后端
public static void downLoad(String path, HttpServletResponse response) {
// 服务器保存的文件地址,即你要下载的文件地址(全路径)
String realpath = System.getProperty("user.dir") + File.separator + path;
File file = new File(realpath);
String fileName = file.getName();
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.addHeader("Content-Length", "" + file.length());
response.setContentType("application/octet-stream");
outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(buffer);
outputStream.flush();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}