java文件下载,出现路径找不到File not found(拒绝访问)

(1)可能出现的问题是: File file = new File(文件路径) : 文件路径没有截止到文件名,所以找不到;

(2)下载的文件包含中文字符: 也会出现此问题;

建议下载文件设置为英文字符或数字;

下载文件的流程:


    /**
     * 下载文件
     * @param id
     * @param res
     * @param request
     */
    @ApiOperation(value="下载文件", notes="下载文件", produces="application/json")
    @GetMapping(value="/download/{id}", produces = "application/json")
    public void downloadTemplate(@PathVariable("id") Long id, HttpServletResponse res, HttpServletResponse request) {
        MesProductionFilesEntity entity = mesFilesService.queryObject(id);
        if (null != entity) {
            String filepath = null;
            try {
                filepath =entity.getFilePath();
                downloadResultFile(res, request, filepath, entity.getFileName());
                logger.info("下载成功!");
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("下载文件异常");
            }
        }else {
            logger.error("下载失败:根据ID 未能找到文件信息!");
        }
    }
    /**
     * 下载文件的方法
     * @param res response对象
     * @param filePath 待下载的文件名
     * @param downloadName 下载给用户的文件名
     */
    private void downloadResultFile(HttpServletResponse res, HttpServletResponse request, String filePath, String downloadName) {

        try {
       if (request.getHeader("User-Agent") != null && request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                downloadName = URLEncoder.encode(downloadName, "UTF-8");
            } else {
                downloadName = new String(downloadName.getBytes("UTF-8"), "UTF-8");
            }
        }
        catch (UnsupportedEncodingException ue) {
            logger.error("download filename convert encoding exception ", ue);
        }

        res.setContentType("application/octet-stream");
        res.addHeader("Content-Disposition", "attachment; filename=" + downloadName);
        BufferedInputStream bis = null;
        BufferedOutputStream out = null;
        File file = new File(filePath);
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            out = new BufferedOutputStream(res.getOutputStream());
            byte[] buff = new byte[2048];
            while (true) {
                int bytesRead;
                if (-1 == (bytesRead = bis.read(buff, 0, buff.length))) {
                    break;
                }
                out.write(buff, 0, bytesRead);
            }
            out.flush();
        } catch (IOException e) {
            logger.error("output template file exception", e);
        } finally {
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(out);
        }
    }

猜你喜欢

转载自blog.csdn.net/fxj0720/article/details/80050190