java使用浏览器请求下载pdf文件

Posted 橙香五花肉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java使用浏览器请求下载pdf文件相关的知识,希望对你有一定的参考价值。

java使用浏览器请求下载pdf文件

代码

/**
 * 下载pdf文件
 *
 * @param pdfFileUrl 文件地址
 * @param fileName   文件名称
 */
public static void downloadPdf(String pdfFileUrl, String fileName) 

    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();

    if (null == requestAttributes) 
        throw new RuntimeException("请求失败");
    
    HttpServletResponse response = requestAttributes.getResponse();

    ServletOutputStream outputStream = null;
    InputStream inputStream = null;

    try 
        // 获取网络文件
        URL urlFile = new URL(pdfFileUrl);
        HttpURLConnection conn = (HttpURLConnection) urlFile.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);

        // 通过输入流获取图片数据
        inputStream = conn.getInputStream();

        // 文件类型
        response.setContentType("application/pdf");
        // 设置请求头
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 获取输出流
        outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while( (len = inputStream.read(buffer)) != -1 )
            outputStream.write(buffer, 0, len);
        

        outputStream.flush();
     catch (Exception e) 
        log.error("【下载PDF文件失败】原因:", e.getMessage());
        e.printStackTrace();
     finally 
        try 
            if (null != inputStream) 
                inputStream.close();
            
            if (null != outputStream) 
                outputStream.close();
            
         catch (Exception ignored) 
    

随便写个控制器调用该方法...启动(方法省略)

打开浏览器访问你写的方法

Pdf下载使用java jersey和spring security在给出邮递员的请求时给出错误

我正在使用以下邮递员“发送和下载按钮”来点击jersy API,但我无法下载pdf而不是只有正常文件被下载。如果我评论@RolesAllowed(“ROLE_USER”)和dircetly从浏览器点击API然后它似乎工作正常,但我想要spring security.please建议解决这个问题

enter image description here

JAVA CODE

  @GET
    @Path("/{userId}/resume/downloadpdf")
    @Produces("application/pdf")
    @ApiOperation(value = "Gets user resume pdf",
            response = Response.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "UserResume information found"),
            @ApiResponse(code = 401, message = "Unauthorized request"),
            @ApiResponse(code = 404, message = "UserResume information not found"),
            @ApiResponse(code = 400, message = "Bad request"),
            @ApiResponse(code = 500, message = "Unknown internal server error")
    })
   @RolesAllowed("ROLE_USER")
    @Override
    public Response downloadResumePdf(@PathParam("userId") String userId) throws IOException, DocumentException {


        String resumeHTMLData ="<h1> hi </h1>";

        StreamingOutput fileStream  = new StreamingOutput() {
            @Override
            public void write(OutputStream output) {
                try {
                    ITextRenderer renderer = new ITextRenderer();
                    renderer.setDocumentFromString(resumeHTMLData);
                    renderer.layout();
                    renderer.createPDF(output);
                    output.flush();
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        };

         return Response.ok(entity)
            .header("Content-Disposition", "attachment; filename="Resume" + LocalDateTime.now().toLocalDate() + ".pdf"")
     .build();


    }

配置类

    @Configuration
    public class OAuthSecurityConfig {

        private static final String USER_ACCOUNTS_RESOURCE_ID = "useraccounts";

        @Configuration
        @Import(SecurityConfig.class)
        @EnableAuthorizationServer
        @PropertySource("classpath:application.properties")
        protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

            @Value("#{environment}")
            private Environment environment;

            @Autowired
            @Qualifier("authenticationManagerBean")
            private AuthenticationManager authenticationManager;

            @Autowired
            private ResourceLoader resourceLoader;



            @Value("${JWT_SHARED_SECRET:test}")
            private String JWT_SHARED_SECRET;

            @Value("${authorization.server:test}")
            private String authorizationServer;

            @Autowired
            private UserDetailsService userDetailsService;

            @Autowired
            @Qualifier("mongoClientDetailsService")
            private ClientDetailsService mongoClientDetailsService;

            @Override
            public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

                ClientDetailsServiceBuilder clientDetailsServiceBuilder =
                        clients.withClientDetails(mongoClientDetailsService);

            }

            @Override
            public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
                endpoints
                        .tokenStore(tokenStore())
                        .tokenEnhancer(tokenEnhancer())
                        .authenticationManager(authenticationManager)
                        .userDetailsService(userDetailsService);
            }

            @Override
            public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
                oauthServer.realm( authorizationServer + "/client")
                        .allowFormAuthenticationForClients();
            }

            @Bean
            public TokenStore tokenStore(){
                return new JwtTokenStore(tokenEnhancer());
            }

            @Bean
            public JwtAccessTokenConverter tokenEnhancer(){
                JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
                tokenConverter.setSigningKey(JWT_SHARED_SECRET);

                return tokenConverter;
            }

        }

        @Configuration
        @EnableResourceServer
        protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {

            @Autowired
            private TokenStore tokenStore;

            @Override
            public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
                resources.resourceId(USER_ACCOUNTS_RESOURCE_ID).stateless(true);
                resources.tokenStore(tokenStore);
            }

            @Override
            public void configure(HttpSecurity http) throws Exception {
                http
                        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                        .and()
                        .requestMatchers().antMatchers("/oauth/admin/**", "/oauth/users/**", "/oauth/clients/**", API_REQUEST_ANT_MATCHER)
                        .and()
                        .authorizeRequests()
                        .antMatchers(API_REQUEST_ANT_MATCHER).permitAll()
                        .antMatchers(API_DOCS_REQUEST_ANT_MATCHER).permitAll()
                        .antMatchers(API_FILTER_CONTEXT + "/swagger.json").permitAll() //Allowing swagger.json for now
                        .regexMatchers(HttpMethod.DELETE, "/oauth/users/([^/].*?)/tokens/.*")
                            .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') " +
                                    "or #oauth2.isClient()) and #oauth2.hasScope('write')")
                        .regexMatchers(HttpMethod.GET, "/oauth/clients/([^/].*?)/users/.*")
                            .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') " +
                                    "or #oauth2.isClient()) and #oauth2.hasScope('read')")
                        .regexMatchers(HttpMethod.GET, "/oauth/clients/.*")
                            .access("#oauth2.clientHasRole('ROLE_CLIENT') " +
                                    "and #oauth2.isClient() and #oauth2.hasScope('read')");
            }
        }

    }

> SecurityConfig class

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Autowired
    @Qualifier("bCryptEncoder")
    PasswordEncoder passwordEncoder;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .regexMatchers("/swagger/((css|images|fonts|lang|lib)/)?(w|.|-)*")
                .regexMatchers("/app/((css|images|fonts|lang|lib)/)?(w|.|-)*")
                .antMatchers("/oauth/uncache_approvals", "/oauth/cache_approvals");
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        return new MongoDBUserDetailsService();
    }

    @Bean
    public ClientDetailsService mongoClientDetailsService() {
        return new MongoDBClientDetailsService();
    }

    @Bean
    public AuthenticationProvider daoAuthenticationProvider() {

        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService());
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);

        return daoAuthenticationProvider;
    }

    /**
     * TODO: Using default spring pages for login/logout processing
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().hasRole("USER")
                .and()
                // TODO: put CSRF protection back into this endpoint
                .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
                .logout()
                .and()
                .formLogin();
    }
}
答案

解决方案1:将物理文件保存到磁盘并在Response中传递文件对象。

解决方案2:将InputStream传递给Response。

我希望它有所帮助。

另一答案

您必须使用以下注释来启用方法级安全性。这是在SecurityConfig内部配置的Web安全性之上的额外级别安全性。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter

启用后,您可以使用@RolesAllowed注释

@RolesAllowed("ROLE_USER")
@Override
public Response downloadResumePdf(@PathParam("userId") String userId) 

以上是关于java使用浏览器请求下载pdf文件的主要内容,如果未能解决你的问题,请参考以下文章

通过 XHR 请求下载 PDF 文件

NX怎么将PDF文件放进浏览器

使用 Python 请求模块下载并保存 PDF 文件

java实现在线浏览PDF文档功能

Java环境中,word文档转PDF直接打开浏览而非下载

使用ajax请求在浏览器中下载