文件下载

来源:互联网 发布:mac 播放器 自动字幕 编辑:程序博客网 时间:2024/06/05 08:00

文件下载

先查询已经上传的文件记录集合。在进行文件下载controller层       @RequestMapping("/list")public ModelAndView main(HttpServletResponse response) {ModelAndView mav = new ModelAndView("page.operate.document");List<OperateDocumentEntity> entities = null;try {entities = operateDocumentService.queryByCondition();} catch (Exception e) {LOG.error("查找操作指南文档列表异常,error={}", e);}mav.addObject("entities", entities);return mav;}
serviceimpl层

@Overridepublic List<OperateDocumentEntity> queryByCondition() {List<OperateDocumentEntity> entity=operateDocumentMapper.queryByCondition();return entity;}
mapper
/** * 查询文件列表 * @return */List<OperateDocumentEntity> queryByCondition();

mapper.xml

<select id="queryByCondition" resultMap="base_result_map" parameterType="com.qbao.signature.entity.OperateDocumentEntity">select  <include refid="Base_Column_List"/>from operate_documentwhere flag='1' order by id DESC LIMIT 3</select>

jsp代码

entities: 已经上传成功的文件对象列表

 <section class="main">        <div class="auto-center contant">            <div class="guide-nav guide-download">                <h2>操作指南</h2>                <div><span>当前位置:首页 > 操作指南</span></div>            </div>            <ul class="guide-down">            <c:forEach items="${entities}" var="debitCardBank" varStatus="status"><li><h3>操作指南${status.count}</h3><p><span title="${debitCardBank.docName }">${debitCardBank.docName }</span></p>                    <a id ="${debitCardBank.id}" class="tool-btn down-btn" href="javascript:void(0)">点击下载</a></li></c:forEach>            </ul>        </div>    </section>
js.代码
<script type="text/javascript">$(document).ready(function(){$(".down-btn").click(function(){window.location.href="/operate/document/downloads?id="+this.id;});});</script>

controller

/** * 文件下载 * @param id * @param request * @param response * @return */@RequestMapping("/downloads")public String download(Integer id, HttpServletRequest request,HttpServletResponse response) {try {// 通过id获取信息OperateDocumentEntity entity = operateDocumentService.selectById(id);// 获取文件名String fileName = entity.getDocName();// 获取文件的下载路径String filePath = entity.getDownloadPath();//响应的编码方式为utf-8 response.setCharacterEncoding("utf-8");//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型  response.setContentType("multipart/form-data");// 处理下载弹出框名字的编码问题    设置文件头:最后一个参数是设置下载文件名(假如我们叫.doc)  response.setHeader("Content-Disposition", "attachment;fileName="+ new String(fileName.getBytes("gb2312"), "ISO8859-1")+ ".doc");// 利用输入输出流对文件进行下载InputStream inputStream = new FileInputStream(new File(filePath));OutputStream os = response.getOutputStream();byte[] b = new byte[2048];int length;while ((length = inputStream.read(b)) > 0){os.write(b, 0, length);}// 这里主要关闭。os.close();inputStream.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}




原创粉丝点击