在获取的一个文件流后,如何将这个流以文件的形式在jsp页面上下载下来?
废话少说,直接上代码:
后台程序:
InputStream input = new ByteArrayInputStream(in2bddd); //input为已知的文件流
response.reset();//清空输出流
response.setHeader("Content-disposition", "attachment; filename=" + this.toUtf8String(fname));//设定输出文件头
response.setContentType("application/x-download");//定义输出类型
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int j = -1;
while ((j = input.read(buffer)) != -1) {
outputStream.write(buffer, 0, j);
}
outputStream.flush();
outputStream.close();
input.close();
outputStream = null;
前台jsp页面的js请求代码:
var urlString = '${contextPath}/sys/fileManage/downLoadFile?id='+idd;
window.open(urlString);
----------------------------------------------------------------------------------------------------------
附加utf-8字符串转换函数:
public static String toUtf8String(String s) {
StringBuffer sb = new StringBuffer();
for (int i=0;i<s.length();i++){
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) k += 256;
sb.append("%" + Integer.toHexString(k).
toUpperCase());
}
}
}
return sb.toString();
}