Spring mvc 下载

来源:互联网 发布:好玩的钢琴软件 编辑:程序博客网 时间:2024/06/03 20:07

Spring mvc 实现文件下载

 

@RequestMapping(value ="/down.action")public void down(HttpServletRequest request,HttpServletResponse response,@RequestParam("id")String id) throws IOException{// 通过前段jsp页面 传过来的id 得到对象 再查出文件下载的pathUserInfoPO po =new UserInfoPO();po.setId(id);// 上传的时候 将文件的path记录在数据库中。
                po=userInfoService.query(po);String fileName =po.getFileNamePath();// 得到文件的全路径加名字if(fileName.isEmpty()){response.getWriter().write("文件不存在");}File file = new File(fileName);InputStream inputstream =new FileInputStream(file);String destFileName = file.getName();download(response, inputstream, destFileName);}

download 方法

protected void download(HttpServletResponse response,InputStream inputStream, String destFileName) throws IOException {response.setContentType("application/octet-stream");response.setCharacterEncoding("UTF-8");String downLoad = "";if (destFileName != null) {downLoad = new String(destFileName.getBytes("GBK"), "ISO-8859-1");}response.setHeader("Content-disposition", "attachment;filename=\""+ downLoad + "\"");OutputStream output = null;try {byte[] bytes = new byte[1024];output = response.getOutputStream();int byteRead;while ((byteRead = inputStream.read(bytes)) != -1) {output.write(bytes, 0, byteRead);}output.flush();}catch (Exception ex) {throw new IOException(ex.getMessage());}finally {if (inputStream != null) {try {inputStream.close();}catch (Exception e) {}}if (output != null) {try {output.close();}catch (Exception e) {}}response.flushBuffer();}}


1 0
原创粉丝点击