本文章向大家介绍Java从服务器读取文件并下载到本地,主要包括Java从服务器读取文件并下载到本地使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
项目和文件不在同一个服务器,a标签下载文件无法解决文件名过长报错的情况,所以只能通过后台下载设置文件名。 也就是用户不是直接通过文件服务器下载,而是先经过后台,后台从文件服务器读取该文件,然后在写给用户。 @RequestMapping("downloadFile") public void download(String id, HttpServletResponse response){ //获取该文件的名称、后缀 SysFile sysFile = sysFileService.selectById(id); //文件在服务器的路径 String path = ConstantFactory.me().getfdfsStorage()+sysFile.getGroup()+"/"+sysFile.getPath(); InputStream inputStream = null; OutputStream out = null; try { //根据文件在服务器的路径读取该文件转化为流 URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); inputStream = conn.getInputStream(); //创建一个Buffer字符串 byte[] buffer = new byte[1024]; String fileName = sysFile.getYm()+sysFile.getHz(); //abcd.png //设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("multipart/form-data"); //设置文件头:最后一个参数是设置下载文件名(设置编码格式防止下载的文件名乱码) response.setHeader("Content-Disposition", "attachment;fileName="+new String( fileName.getBytes("gb2312"), "ISO8859-1" )); out = response.getOutputStream(); int b = 0; while (b != -1){ b = inputStream.read(buffer); //写到输出流(out)中 out.write(buffer,0,b); } }catch (Exception e){ e.printStackTrace(); }finally { try { inputStream.close(); out.close(); out.flush(); }catch (Exception e){ e.printStackTrace(); } } } (责任编辑:) |