文件下载
java代码:
@RequestMapping("/downcsv") public void downcsv(String filePath ,HttpServletResponse response){ PrintWriter out=null; BufferedReader bReader=null; try { // // 获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载 // String path = request.getServletContext().getRealPath("/"); if(StringUtils.isBlankOrNull(filePath)){ myLogger.info("文件地址错误"); return; } String name =filePath.substring(filePath.lastIndexOf("/")); name = new String(name.getBytes(), "ISO-8859-1");//文件名乱码处理 // 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("multipart/form-data"); // 2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf) response.setHeader("Content-Disposition", "attachment;fileName=" + name); // 3.通过response获取ServletOutputStream对象(out) out = response.getWriter(); bReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"UTF-8")); String line = ""; out.write("\ufeff");//保存为csv乱码处理 while ((line = bReader.readLine()) != null) { out.write(line+"\n"); } } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.flush(); out.close(); } try { if(null!=bReader){ bReader.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
js提交:
var url="taskExport/downcsv"; var filePath=data.file_url; var form = $("<form></form>").attr("action", url).attr("method", "post"); form.append($("<input></input>").attr("type", "hidden").attr("name", "filePath").attr("value", filePath)); form.appendTo('body').submit().remove();