/**
* 通过文件路径下载文件
*
* @param filePath 文件路径
* @param response
* @throws Exception
*/
public int download(String filePath, String attachmentName,HttpServletResponse response) throws Exception {
// 判断文件是否存在
File file = new File(filePath);
logger.info("DOWNLOAD PATH:" + filePath);
if (!file.exists() || file.isDirectory()) {
logger.info("FILE DOES NOT EXIST!");
return 0;
}
// 自定义文件名
String filename = file.getAbsolutePath();
String suffix = filename.substring(filename.lastIndexOf("."));
//根据UUID重命名文件
// String attachmentName = IdUtils.getId() + suffix;
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(attachmentName, "UTF-8"));
InputStream in = null;
BufferedInputStream bis = null;
OutputStream out = null;
BufferedOutputStream bos = null;
try {
in = new FileInputStream(filePath);
bis = new BufferedInputStream(in);
byte[] data = new byte[1024];
int bytes = 0;
out = response.getOutputStream();
bos = new BufferedOutputStream(out);
while ((bytes = bis.read(data, 0, data.length)) != -1) {
bos.write(data, 0, bytes);
}
bos.flush();
return 1;
} catch (Exception e) {
logger.error("THE REQUEST FAILED:" + e.getMessage(), e);
throw new Exception("THE REQUEST FAILED!");
} finally {
try {
if (bos != null) {
bos.close();
}
if (out != null) {
out.close();
}
if (bis != null) {
bis.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 下载文件
*
* @param path 文件的位置
* @param fileName 自定义下载文件的名称
* @param resp http响应
* @param req http请求
*/
// 字符编码格式
private static String charsetCode = "utf-8";
public static int downloadFile(String path, String fileName, HttpServletResponse resp, HttpServletRequest req) {
int i;
try {
File file = new File(path);
/**
* 中文乱码解决
*/
String type = req.getHeader("User-Agent").toLowerCase();
if (type.indexOf("firefox") > 0 || type.indexOf("chrome") > 0) {
/**
* 谷歌或火狐
*/
fileName = new String(fileName.getBytes(charsetCode), "iso8859-1");
} else {
/**
* IE
*/
fileName = URLEncoder.encode(fileName, charsetCode);
}
// 设置响应的头部信息
resp.setHeader("content-disposition", "attachment;filename=" + fileName);
// 设置响应内容的类型
resp.setContentType(getFileContentType(fileName) + "; charset=" + charsetCode);
// 设置响应内容的长度
resp.setContentLength((int) file.length());
// 输出
outStream(new FileInputStream(file), resp.getOutputStream());
i = 1;
} catch (Exception e) {
System.out.println("执行downloadFile发生了异常:" + e.getMessage());
i = 0;
}
return i;
}
/**
* 文件的内容类型
*/
private static String getFileContentType(String name) {
String result = "";
String fileType = name.toLowerCase();
if (fileType.endsWith(".png")) {
result = "image/png";
} else if (fileType.endsWith(".gif")) {
result = "image/gif";
} else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) {
result = "image/jpeg";
} else if (fileType.endsWith(".svg")) {
result = "image/svg+xml";
} else if (fileType.endsWith(".doc")) {
result = "application/msword";
} else if (fileType.endsWith(".xls")) {
result = "application/x-excel";
} else if (fileType.endsWith(".zip")) {
result = "application/zip";
} else if (fileType.endsWith(".pdf")) {
result = "application/pdf";
} else {
result = "application/octet-stream";
}
return result;
}
/**
* 基础字节数组输出
*/
private static void outStream(InputStream is, OutputStream os) {
try {
byte[] buffer = new byte[10240];
int length = -1;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
os.flush();
}
} catch (Exception e) {
System.out.println("执行 outStream 发生了异常:" + e.getMessage());
} finally {
try {
os.close();
} catch (IOException e) {
}
try {
is.close();
} catch (IOException e) {
}
}
}
/**
* 从网络Url中下载文件
*
* @param urlStr
* @param fileName
* @param savePath
* @throws IOException
*/
public static int downLoadFromUrl(String urlStr, String fileName, String savePath) {
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// 得到输入流
InputStream inputStream = conn.getInputStream();
// 获取自己数组
byte[] getData = readInputStream(inputStream);
// 文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
// System.out.println("info:"+url+" download success");
// return saveDir + File.separator + fileName;
return 1;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 从输入流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
public void getFile(HttpServletResponse response,String localMapJsonPath, String fileName) throws Exception {
File localMapJsonDir = new File(localMapJsonPath);
if (!localMapJsonDir.exists()) {
throw new Exception("文件夹不存在: " + localMapJsonPath);
}
String filePath = localMapJsonPath + "/" + fileName;
File file = new File(filePath);
InputStream inputStream = null;
if (!file.exists()) {
throw new Exception("文件不存在: " + filePath);
}
ServletOutputStream outputStream = response.getOutputStream();
try {
inputStream = new FileInputStream(file);
byte[] buf = new byte[1024];
int readLength = inputStream.read(buf);
while (readLength != -1) {
outputStream.write(buf, 0, readLength);
readLength = inputStream.read(buf);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
IOUtils.closeQuietly(outputStream);
IOUtils.closeQuietly(inputStream);
}
}
以上方法自行测试!!!
以下是我自己测试成功的例子(仅供参考):
后台
@RequestMapping("/downloadMylData")
public void downloadMylData(@RequestParam(name = "type") String type,
@RequestParam(name = "time") String time,
@RequestParam(name = "eleName") String eleName,
@RequestParam(name = "ybSection") String ybSection,
@RequestParam(name = "timeNode") String timeNode,
HttpServletResponse response) throws Exception {
// String sql = "SELECT\n" +
// "\tSRC\n" +
// "FROM\n" +
// "\tTASK_DATA_SAVE\n" +
// "WHERE\n" +
// "\tMODULETYPE = '" + type + "'\n" +
// "AND STARTTIME = '" + time + "'\n" +
// "AND ELETYPE = '" + eleName + "'\n" +
// "AND AGING = '" + timeNode + "'\n" +
// "AND SCALE = '" + ybSection + "'";
//
// List<Map<String, Object>> maps = priJdbcTemplate.queryForList(sql);
// String filePath = null;
// if (maps != null && maps.size() > 0) {
// filePath = maps.get(0).get("SRC").toString();
// } else {
// logger.info("无此文件路径");
// return;
// }
// String fileName = filePath.split("\\\\")[6] + "-" + filePath.split("\\\\")[7] + "-" + filePath.split("\\\\")[8];
/* String localPath = "D:/downloadFile/" + filePath.split("\\\\")[6] + "-" + filePath.split("\\\\")[7];
File localFile = new File(localPath);
if (!localFile.exists()) {
localFile.mkdirs();
}*/
// //本地测试
String filePath = "C:\\Users\\84695\\Desktop\\GDS\\ECMWF_HR\\RAIN24\\19061408.024";
String fileName = "ECMWF_HR-RAIN24-19061408.024";
boolean flag = downFile(fileName, response, filePath);
if (flag) {
logger.info(fileName + "文件下载成功!");
} else {
logger.info("文件下载失败");
}
}
/**
* 描述: 下载资料
*
* @author: css
* @create: 2019/10/17 14:00
*/
public boolean downFile(String fileName, HttpServletResponse response, String filePath) {
boolean flag = false;
File file = new File(filePath);
if (file.exists()) {
// String[] split = filePath.split("\\\\");
response.setContentType("application/force-download");// 设置强制下载不打开
try {
response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName + ".zip", "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream outputStream = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = bis.read(buffer);
}
// return true;
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return flag;
}
前台
<div class="index-form" id="index-operation-btn">
<a href="javascript:void(0);" class="btn btn-xs btn-default" name="下载资料" id="myDownload" style="margin-top: 5px;">下载资料</a>
</div>
/*点击下载资料按钮*/
downloadMylData: function () {
$('#index-operation-btn a[name="下载资料"]').click(function () {
var self = this;
var title = $(".index-map-title b").text();
var titleArray = title.split("-");
var type = $('#index-moduleTpe-select option:selected').val(); // 数据的类型
var time = titleArray[2];
var eleName = 'RAIN';
var ybSection = titleArray[1].split("RAIN")[1];
var timeNode = titleArray[3];
//本地
$('#index-operation-btn a[name="下载资料"]').attr('href', "http://localhost:7777/downloadMyData?type="+type+"&time="+time+"&eleName="+eleName+"&ybSection="+ybSection+"&timeNode="+timeNode);
});
// 这个也可以
// window.location.href = "http://localhost:7777/CJLY3/gridCW/downloadMylData?type=" +
// type + "&time=" + time + "&eleName="+ eleName + "&ybSection=" + ybSection + "&timeNode=" + timeNode;
},
能触发浏览器下载的url有两类:
response header
——指定了Content-Disposition
为attachment
,它表示让浏览器把响应体作为附件下载到本地 (一般Content-Disposition
还会指定filename
, 下载的文件默认就是filename指定的名字)response header
——指定了Content-Type
为application/octet-stream(无类型)
或者application/zip(下载zip包时)
以及其它几个不常见类型 (其中还有浏览器差异),其中application/octet-stream
表示http response
为二进制流(没指定明确的type), 需要下载到本地, 由系统决定或者用户手动指定打开方式。
网友评论