【问题标题】:No able to download .xlsx file in jsp无法在jsp中下载.xlsx文件
【发布时间】:2020-03-21 20:48:58
【问题描述】:
我为下载文件编写了如下代码:
String filename = request.getParameter("file").toString();
String filepath = request.getParameter("path").toString(); ;
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
FileInputStream fileInputStream=new FileInputStream(filepath + filename);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
【问题讨论】:
标签:
java
file
jsp
file-upload
【解决方案1】:
我在带有 scriplet 标签的 jsp 页面中使用此代码,即
现在我在 servlet 中尝试过,现在可以打开 .xlsx 文件。工作代码如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String filename = request.getParameter("file").toString();
String filepath = request.getParameter("path").toString();
File f = new File (filepath + filename);
//set the content type(can be excel/word/powerpoint etc..)
String type = request.getParameter("type");
response.setContentType (type);
//set the header and also the Name by which user will be prompted to save
response.setHeader ("Content-Disposition", "attachment; filename=\""+filename+"\"");
//get the file name
String name = f.getName().substring(f.getName().lastIndexOf("/") + 1, f.getName().length());
//OPen an input stream to the file and post the file contents thru the
//servlet output stream to the client m/c
InputStream in = new FileInputStream(f);
try{
ServletOutputStream outs = response.getOutputStream();
int bytesRead;
byte[] buf = new byte[4 * 1024]; // 4K buffer
try {
while ((bytesRead = in.read(buf)) != -1){
outs.write(buf, 0, bytesRead);
}
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
outs.flush();
outs.close();
in.close();
}catch(Exception e){
e.printStackTrace();
}
}