两个工具方法
1、下载文件到浏览器
2、保存指定url的文件
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;
/**
* 文件下载
*
*/
@Slf4j
public class FileDownloadUtil {
/**
* 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) {
return false;
}
}
}