在Springboot中从项目中读取文件并下载时 ResourceUtils.getFile返回路径出错解决方案

1.本地使用ResourceUtils.getFile没有任何问题,打成jar包后部署到服务器上报错

错误原因:

ResouceUtils.getFile()是专门用来加载非压缩文件类型的资源的,所以它根本不会去读取jar包中的资源,本地之所以没事是因为本地访问的不是jar而是直接编译的,

解决方法:

要想读取jar包中的文件,只能通过流来进行读取。可以使用new ClassPathResource(filepath);

代码

public  void downloadCompanyTemplate(HttpServletRequest request, HttpServletResponse response, String fileType)
        throws IOException
{
InputStream inputStream = null;
String filename = null;
ClassPathResource resource = = new ClassPathResource(filepath);
filename = resource.getFilename();
inputStream = resource.getInputStream();

getWordByInputStream(response, inputStream, filename);
}


public void getWordByInputStream(HttpServletResponse response, InputStream
        inputStream, String filename) throws UnsupportedEncodingException
{
    BufferedInputStream bis = null;
    OutputStream out = null;
    String ext = filename.substring(filename.lastIndexOf(".") + 1);
    filename = new String(filename.getBytes(), "ISO-8859-1");   //UTF-8编码,防止输出文件名乱码
    // 设置response参数,可以打开下载页面
    response.setHeader("Content-Disposition", "attachment;filename=" + filename);
    if ("docx".equals(ext) || "doc".equals(ext))
    {
        response.setContentType("application/msword"); // word格式
    } else if ("pdf".equals(ext))
    {
        response.setContentType("application/pdf"); // word格式
    }
    try
    {
        out = response.getOutputStream();
        bis = new BufferedInputStream(inputStream);
        byte[] buff = new byte[1024 * 2];
        int count = -1;
        out = response.getOutputStream();   //直接下载导出
        while ((count = bis.read(buff)) != -1)
        {
            out.write(buff, 0, count);
        }
        out.flush();
        out.close();

    } catch (IOException e)
    {

    } finally
    {
        if (out != null)
        {
            try
            {
                out.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lixiaohai_918/article/details/82015000
今日推荐