加载中...
加载中...
JAVA下载文件工具类

JAVA下载文件工具类 原创

JAVA下载文件工具类

复制收展Javapackage com.nstc.iface.handler;
import com.nstc.smartform.core.ContextUtils;
import com.nstc.smartform.core.RequestContext;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
* <p>
* Title: 下载文件工具类
* </p>
*
* <p>
* Description: 下载文件工具类
* </p>
*
* <p>
* Company:
* </p>
*
* @author luolei
*
* @since:2021-12-24
*
*/
public class DownloadFileUtils {

/**
* 下载附件 返回文件
* @param requestContext
* @throws Exception
*/
public static void download(RequestContext requestContext) throws Exception {
HttpServletResponse response=(HttpServletResponse) ContextUtils.getHttpContext().getResponse();
String id = requestContext.getParameter("fileId");
/**根据id取得文件的名字和路径**/
/**附件路径**/
String fileName = "";
/**附件名称**/
String fatTitel = "";
if (!"".equals(fileName) && !"".equals(fatTitel)) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
File file = new File(fileName);
if (!file.exists()) {
throw new RuntimeException("资料文件“" + fileName + "”不存在!");
}
response.reset();
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(fatTitel, "UTF-8").replace('+', ' '));
response.setHeader("Content_Length", String.valueOf(file.length()));
inputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
byte[] buff = new byte[2048];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buff, 0, buff.length)) > 0) {
outputStream.write(buff, 0, bytesRead);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
/**
* throw new RuntimeException(e.getMessage());从finally块返回,中断,抛出等等会抑制在try或catch块中抛出的任何未处理的Throwable的传播。
*/
}
if (outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
/**
* throw new RuntimeException(e.getMessage());
*/
}
}
}
}
}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87


没有更多推荐了 [去首页]
image
文章
357
原创
284
转载
73
翻译
0
访问量
199056
喜欢
47
粉丝
6
码龄
5年
资源
0

文章目录

加载中...
1
1