java使用流实现浏览器下载docx文件
转载自:https://blog.csdn.net/yytoo2/article/details/79971094
后端代码如下:需要注意的是头的设置,需要告诉浏览器需要下载文件,以及下载文件名。
在这里我下载的是一个docx文件
/**
* 导出
* @param aFileName
* @param aFilePath
*/
public void doExport(String aFileName, String aFilePath,HttpServletRequest request, HttpServletResponse response){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File file = null;
file = new File(aFilePath);
try{
request.setCharacterEncoding("UTF-8");
String agent = request.getHeader("User-Agent").toUpperCase();
if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
aFileName = URLEncoder.encode(aFileName, "UTF-8");
else {
aFileName = new String(aFileName.getBytes("UTF-8"), "ISO8859-1");
}
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + aFileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
bos.write(buff, 0, bytesRead);
System.out.println("success");
bos.flush();
}catch (Exception e) {
// TODO: handle exception
System.out.println("导出文件失败!");
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
file.delete();
} catch (Exception e) {
// LOGGER.error("导出文件关闭流出错!", e);
}
}
}
需要下载文件的时候就可以调用该方法:
String tempFilePath = "D:/word/tmp/";
String aFileName = "test.docx";
doExport(aFileName, tempFilePath.concat(aFileName),request,response);
request和response最好是从最开始的方法哪里传递过来,在不同package下可能会出错
然后还需要注意的是,在前端必须使用http请求,而不能使用ajax,否则也会出现fiddler中显示浏览器拿到了数据但是浏览器没反应的情况
前端使用jquery构造一个http请求如下:
function gen(id){
var urlStrl ="你需要提交的url地址";
var inputValue1 = 'xxxx';
var form = $('<form></form>');
form.attr('style', 'display:none');
form.attr('target', '_blank'); //设置_blank后,下载会在新窗口打开,同时保留原来的窗口
form.attr('method', 'post');
form.attr('action', urlStrl);
var input = $('<input type="text" name="XXX" id="param1" />'); // 可以使用input来提交数据
input.attr('value', inputValue1); //在input中放入需要传入的数据
form.append(input);
$(document.body).append(form);
form.submit();
}