JAVA实现文件下载功能

  • Post author:
  • Post category:java


	@GetMapping("readFileUrl")
    @ApiOperation("下载文件")
    @ApiImplicitParam(name = "fileUrl", value = "文件地址", required = true, dataType = "String", paramType = "body")
    public void readFileUrl(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileUrl)
            throws ServletException, IOException {
        if (StringUtils.isBlank(fileUrl)) {
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSONObject.toJSON(new Result().error("参数错误")).toString());
            return;
        }

        URL url = new URL(fileUrl);
        String filename = fileUrl.substring((fileUrl.lastIndexOf('/') + 1));

        BufferedInputStream in = null;
        try {
            // 这和上面两句一样的效果
            in = new BufferedInputStream(url.openStream());
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            // 将网络输入流转换为输出流
            int i;
            while ((i = in.read()) != -1) {
                response.getOutputStream().write(i);
            }
        } catch (IOException e) {
            log.error("IO流异常",e);
        } finally {

            if (in != null ){
                in.close();
            }
            response.getOutputStream().close();

        }
    }



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