Java使用smb方式解决访问共享文件向前端返回文件输出流解决方案

因业务需要,第三方提供图片为共享文件方式进行访问,具体解决方案如下:

我的实现方式为,读取共享文件,将该文件流输出到Response后进行响应

Java实现:

public class SmbUtil {
    private static final Logger logger = LoggerFactory.getLogger(SmbUtil.class);

    /**
     * 使用smb获取文件输出到response
     * @param smbMachine    smb访问地址 smb:\\ip\data\文件名.Jpeg
     * @param username      用户名
     * @param passwd        密码
     * @param domain        远程ip
     * @param contentType   Content-type
     * @param response
     * @return
     */
    public static Boolean getFileToResponse(String smbMachine,
                                             String username,
                                             String passwd,
                                             String domain,
                                             String contentType,
                                             HttpServletResponse response){
        SmbFileInputStream in = null;
        try {
            //先验证
            NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication(
                    domain, username, passwd);
            SmbFile smbFile = new SmbFile(smbMachine, authentication);
            if(!smbFile.exists()){
                logger.error("无法访问目标主机,domain:{}",domain);
                return null;
            }
            in = new SmbFileInputStream(smbFile);
            response.setContentType(contentType); // 不同文件的MimeType参考后续链接
            FileCopyUtils.copy(in, response.getOutputStream());
            return true;
        } catch (IOException ioException) {
            logger.error("使用smb获取文件输出到response发生IO异常,domain:{}",domain,ioException);
        }catch (Exception e){
            logger.error("使用smb获取文件输出到response发生异常,domain:{}",domain,e);
        }finally {
            if (in != null){
                //关闭文件流
                in.close();
            }
        }
        return false;
    }

}

Content-type选择参考:

https://blog.csdn.net/Lieforlove/article/details/90202258

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值