java 存储对象中下载文件,并修改文件名称

/**
  * 通过https下载文件,并修改名称
  * @param fileUrl 下载地址
  * @param fileName 修改名称
  * @param response 返回修改后的文件
  */
  @RequestMapping(value = "/getFile", method = RequestMethod.GET)
  public void getFile(@RequestParam("fileUrl") String fileUrl, @RequestParam("fileName") String fileName, HttpServletResponse response) {
      try {
          URL url = new URL(fileUrl);
          int index = fileUrl.indexOf("?");//第一个问号的位置
          if(index > -1) {
              fileUrl = fileUrl.substring(0, index);
          }
          String[] split = fileUrl.split("\\.");
          // 不同文件的MimeType参考后续链接
          response.setContentType("application/x-download");//下面三行是关键代码,处理乱码问题
          response.setCharacterEncoding("utf-8");
          response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1") + "." + split[split.length-1]);
          URLConnection conn = url.openConnection();
          InputStream inStream = conn.getInputStream();
          OutputStream fos = response.getOutputStream();
          // 读取路径下面的文件
          FileCopyUtils.copy(inStream, fos);
          response.getOutputStream().flush();
          response.getOutputStream().close();
          response.flushBuffer();
      } catch (Exception e) {
          e.printStackTrace();
      }
  }


版权声明:本文为YuChen954原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。