package com.ruoyi.common.utils.file;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
public static void writeBytes(String filePath, OutputStream os) throws IOException
FileInputStream fis = null;
File file = new File(filePath);
throw new FileNotFoundException(filePath);
fis = new FileInputStream(file);
byte[] b = new byte[1024];
while ((length = fis.read(b)) > 0)
public static String writeImportBytes(byte[] data) throws IOException
return writeBytes(data, RuoYiConfig.getImportPath());
public static String writeBytes(byte[] data, String uploadDir) throws IOException
FileOutputStream fos = null;
String extension = getFileExtendName(data);
pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName);
fos = new FileOutputStream(file);
return FileUploadUtils.getPathFileName(uploadDir, pathName);
public static boolean deleteFile(String filePath)
File file = new File(filePath);
if (file.isFile() && file.exists())
public static boolean isValidFilename(String filename)
return filename.matches(FILENAME_PATTERN);
public static boolean checkAllowDownload(String resource)
if (StringUtils.contains(resource, ".."))
if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource)))
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
final String agent = request.getHeader("USER-AGENT");
String filename = fileName;
if (agent.contains("MSIE"))
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
else if (agent.contains("Firefox"))
filename = new String(fileName.getBytes(), "ISO8859-1");
else if (agent.contains("Chrome"))
filename = URLEncoder.encode(filename, "utf-8");
filename = URLEncoder.encode(filename, "utf-8");
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(percentEncodedFileName);
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
response.setHeader("Content-disposition", contentDispositionValue.toString());
response.setHeader("download-filename", percentEncodedFileName);
public static String percentEncode(String s) throws UnsupportedEncodingException
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20");
public static String getFileExtendName(byte[] photoByte)
String strFileExtendName = "jpg";
if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
&& ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97))
strFileExtendName = "gif";
else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70))
strFileExtendName = "jpg";
else if ((photoByte[0] == 66) && (photoByte[1] == 77))
strFileExtendName = "bmp";
else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
strFileExtendName = "png";
return strFileExtendName;
public static String getName(String fileName)
int lastUnixPos = fileName.lastIndexOf('/');
int lastWindowsPos = fileName.lastIndexOf('\\');
int index = Math.max(lastUnixPos, lastWindowsPos);
return fileName.substring(index + 1);
public static String getNameNotSuffix(String fileName)
String baseName = FilenameUtils.getBaseName(fileName);
public static MultipartFile getMultipartFile(File file) {
FileItem item = new DiskFileItemFactory().createItem("file"
, MediaType.MULTIPART_FORM_DATA_VALUE
try (InputStream input = new FileInputStream(file);
OutputStream os = item.getOutputStream()) {
throw new IllegalArgumentException("Invalid file: " + e, e);
return new CommonsMultipartFile(item);
public static void filePath(String path){
File file = new File(path);
public static void copyFile(String oldPath ,String newPath ){
System.out.println("copy file from [" + oldPath + "] to [" + newPath +"]");
File oldFile = new File(oldPath) ;
if(oldFile.isDirectory()){
File newPathDir = new File(newPath);
File[] lists = oldFile.listFiles() ;
if(lists != null && lists.length > 0 ){
for (File file : lists) {
copyFile(file.getAbsolutePath(), newPath.endsWith(File.separator) ? newPath + file.getName() : newPath + File.separator + file.getName()) ;
InputStream inStream = new FileInputStream(oldFile);
FileOutputStream fs = new FileOutputStream(newPath);
write2Out(inStream ,fs) ;
System.out.println("复制文件到新路径失败:"+e.getMessage());
public static void copeZipFile(String oldPath ,String newPath) throws Exception {
FileInputStream fin = new FileInputStream(new File(oldPath));
ZipInputStream zin = new ZipInputStream(fin);
byte[] in_bytes = new byte[1000];
zin.read(in_bytes,0,1000);
FileOutputStream fout = new FileOutputStream(new File(newPath));
ZipOutputStream zout = new ZipOutputStream(fout);
zout.write(in_bytes,0,in_bytes.length);
public static void writeFile(String url, String content) throws Exception {
File file = new File(url);
FileUtils.deleteFile(url);
String writeDate = content;
fw = new FileWriter(file, true);
fw.write(writeDate + "\r\n");
public static File renameFile(File file , String name ){
String fileName = file.getParent() + File.separator + name ;
File dest = new File(fileName);
private static void write2Out(InputStream input , OutputStream out) throws IOException {
byte[] b = new byte[1024];
while ( (c = input.read(b)) != -1 ) {
public static MultipartFile getMultipartFile(File file) {
FileItem item = new DiskFileItemFactory().createItem("file"
, MediaType.MULTIPART_FORM_DATA_VALUE
try (InputStream input = new FileInputStream(file);
OutputStream os = item.getOutputStream()) {
throw new IllegalArgumentException("Invalid file: " + e, e);
return new CommonsMultipartFile(item);
public static File MultipartFileToFile(MultipartFile multiFile) {
String fileName = multiFile.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf("."));
File file = File.createTempFile(fileName, prefix);
multiFile.transferTo(file);
public static String encodeBase64File(File file) throws Exception {
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
return new BASE64Encoder().encode(buffer);

org.apache.commons.io.FileUtils.copyFile(new File(zpiPath),new File(zipurl));