```package com.oristand.starcloud.common.utils;
import com.oristand.starcloud.common.constants.KeyboardSpecialCharConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
/**
* 文件下载
*
* @author peiyuxiang
* @date 2021/05/04
*/
@Slf4j
public class FileDownloadUtil {
/**
* pdf下载流
*/
public static final String APPLICATION_PDF = "application/pdf";
/**
* pdf下载流
*/
public static final String APPLICATION_TEXT_PLAIN = "text/plain";
/**
* http 传输文件
*
* @param response servlet响应
* @param filePath 文件全路径名
* @param fileName 附件文件名
*/
public static void download(HttpServletResponse response,
String filePath,
String fileName,
String contentType
) throws IOException {
if (StringUtils.isBlank(contentType)) {
response.setContentType("application/octet-stream");
} else {
response.setContentType(contentType);
}
try {
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
} catch (Exception e) {
// pass
}
byte[] buff = new byte[1024];
//创建缓冲输入流
BufferedInputStream bis = null;
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
//这个路径为待下载文件的路径
bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
int read = bis.read(buff);
//通过while循环写入到指定了的文件夹中
while (read != -1) {
outputStream.write(buff, 0, read);
outputStream.flush();
read = bis.read(buff);
}
} finally {
if (null != bis) {
try {
bis.close();
} catch (IOException e) {
// 忽略
}
}
if (null != outputStream) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
// 忽略
}
}
}
}
/**
* 用http请求将url文件保存到本地
*
* @param url 请求文件的url
* @param filePath 需要保存的路径
* @return 是否保存文件成功, 成功返回true, 失败返回false
*/
public static boolean saveFileByUrl(URL url, String filePath) {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
DataInputStream inputStream = new DataInputStream(connection.getInputStream());
DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(filePath));
byte[] buffer = new byte[1024];
int count;
while ((count = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, count);
}
outputStream.close();
inputStream.close();
log.info("this is connection success");
return true;
} catch (Exception e) {
log.error("FileDownloadUtil#saveFileByUrl error url:{},filePath:{}", url, filePath);
return false;
}
}
/**
* 将数据保存到path路径
*
* @param inputStream 文件流
* @param savePath 路径:"D:\\testFile\\"
* @param fileName 文件名:text.pdf
*/
public static Boolean saveFileToPath(InputStream inputStream, String savePath, String fileName) {
if (null == inputStream || StringUtils.isBlank(savePath) || StringUtils.isBlank(fileName)) {
return false;
}
FileOutputStream fileOutputStream = null;
DataOutputStream dataOutputStream = null;
try {
//输出的文件流保存到本地文件
File file = new File(savePath);
boolean flag = file.exists();
if (!flag) {
flag = file.mkdirs();
}
if (!flag) {
return false;
}
String finalPath;
if (savePath.endsWith(KeyboardSpecialCharConstants.SLASH) ||
savePath.endsWith(KeyboardSpecialCharConstants.BACKSLASH)) {
finalPath = savePath + fileName;
} else {
finalPath = savePath + KeyboardSpecialCharConstants.SLASH + fileName;
}
fileOutputStream = new FileOutputStream(finalPath);
dataOutputStream = new DataOutputStream(fileOutputStream);
//保存到临时文件
byte[] bs = new byte[1024];
//读取到的数据长度
int len;
while ((len = inputStream.read(bs)) != -1) {
dataOutputStream.write(bs, 0, len);
dataOutputStream.flush();
}
} catch (IOException e) {
log.error("saveFileToPath#error", e);
return false;
} finally {
//完毕,关闭所有链接
try {
inputStream.close();
} catch (IOException e) {
// 忽略
}
if (null != fileOutputStream) {
try {
fileOutputStream.close();
} catch (IOException e) {
// 忽略
}
}
if (null != dataOutputStream) {
try {
dataOutputStream.close();
} catch (IOException e) {
// 忽略
}
}
}
return true;
}
/**
* 创建目录
*
* @param filePath 文件路径
* @return true/false
*/
public static Boolean createDirectory(String filePath) {
if (StringUtils.isBlank(filePath)) {
return false;
}
File file = new File(filePath);
boolean flag = file.exists();
if (!flag) {
flag = file.mkdirs();
}
if (flag) {
return true;
}
log.info("createDirectory Failed#filePath:{}", filePath);
return false;
}
}