通过smb协议上传下载文件到nas
方式一:
需要添加的依赖:
<!--共享目录文件下载操作工具包--><dependency><groupId>com.hierynomus</groupId><artifactId>smbj</artifactId><version>0.10.0</version></dependency>
NasSMBUtil.java 工具类:
package com.cwp.data.application.utils;import com.cwp.data.application.config.NasFileConfig;
import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.mssmb2.SMB2CreateDisposition;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.share.File;
import lombok.extern.slf4j.Slf4j;import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.EnumSet;/*** 远程共享目录操作工具类*/
@Slf4j
public class NasSMBUtil {//private static final String SHARE_DOMAIN = "DOMAIN";// private static final String searchPattern_JSON = "*.json";private static final String FILE_SEPERATE = "/";public static boolean downloadRemoteFileByPathAndConfig(String host, String remoteDir, String filename, String localDestFilePath, NasFileConfig fileConfig) {// 设置超时时间(可选)
// SmbConfig config = SmbConfig.builder()
// .withTimeout(300, TimeUnit.SECONDS) // Timeout sets Read, Write, and Transact timeouts (default is 60 seconds)
// .withSoTimeout(300, TimeUnit.SECONDS) // Socket Timeout (default is 0 seconds, blocks forever)
// .build();log.error("fileConfig:{} ,remoteDir:{}", fileConfig, remoteDir);String[] dirArr = remoteDir.split(FILE_SEPERATE);String rootDir = dirArr[1] + FILE_SEPERATE;String secDir = dirArr[2] + FILE_SEPERATE;log.info("rootDir:{}, secDir:{}", rootDir, secDir);boolean isDownloadSuccess = false;try (SMBClient client = new SMBClient()) {Connection connection = client.connect(host);AuthenticationContext ac = new AuthenticationContext(fileConfig.getAccount(), fileConfig.getPassword().toCharArray(), null);Session session = connection.authenticate(ac);log.info("共享目录权限认证成功");// 连接共享文件夹DiskShare share = (DiskShare) session.connectShare(rootDir);log.info("进入文件目录:====> {}", rootDir);//共享目录图片地址String filePath = secDir + filename;//需要下载到本地的图片地址BufferedOutputStream bos = null;InputStream ins = null;try {bos = new BufferedOutputStream(new FileOutputStream(localDestFilePath));log.info("=================开始下载文件: {}", filePath);File smbFileRead = share.openFile(filePath, EnumSet.of(AccessMask.GENERIC_READ), null, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OPEN, null);ins = smbFileRead.getInputStream();log.info("smbFileRead inputStream的hashcode:{}", ins.hashCode());byte[] buffer = new byte[4096];int len;while ((len = ins.read(buffer, 0, buffer.length)) != -1) {bos.write(buffer, 0, len);}bos.flush();log.info("==============={} 文件下载成功!", filename);isDownloadSuccess = true;} catch (Exception e) {e.printStackTrace();} finally {closeStream(bos, ins);}} catch (IOException e) {e.printStackTrace();}return isDownloadSuccess;}private static void closeStream(BufferedOutputStream bos, InputStream ins) {if (null != bos) {try {bos.close();} catch (IOException e) {e.printStackTrace();}}if (null != ins) {try {ins.close();} catch (IOException e) {e.printStackTrace();}}}}
方式二:
添加依赖:
<dependency><groupId>jcifs</groupId><artifactId>jcifs</artifactId><version>1.3.17</version></dependency>
工具类:
NasSmbJcifsUtils.java
package cn.getech.data.development.utils;import cn.getech.data.intelligence.common.exception.RRException;
import jcifs.smb.*;
import lombok.extern.slf4j.Slf4j;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.net.UnknownHostException;/*** @ClassName NasSMBUtils* @Description TODO* @Author Getech* @Date 2021/7/6 11:22*/
@Slf4j
public class NasSmbJcifsUtils {private static final String FILE_SEPERATE = "/";/*** 读取共享文件夹下的所有文件(文件夹)的名称* @param remoteUrl*/public static void getSharedFileList(String remoteUrl) {SmbFile smbFile;try {// smb://userName:passWord@host/path/smbFile = new SmbFile(remoteUrl);if (!smbFile.exists()) {System.out.println("no such folder");} else {SmbFile[] files = smbFile.listFiles();for (SmbFile f : files) {System.out.println(f.getName());}}} catch (MalformedURLException e) {e.printStackTrace();throw new RRException(e.getMessage());} catch (SmbException e) {e.printStackTrace();throw new RRException(e.getMessage());}}/*** 创建文件夹* @param remoteUrl* @param folderName* @return*/public static void smbMkDir(String remoteUrl, String folderName) {SmbFile smbFile;try {// smb://userName:passWord@host/path/folderNamesmbFile = new SmbFile(remoteUrl + folderName);if (!smbFile.exists()) {smbFile.mkdir();}} catch (MalformedURLException e) {e.printStackTrace();} catch (SmbException e) {e.printStackTrace();}}/*** 上传文件* @param remoteUrl* @param shareFolderPath* @param localFilePath* @param fileName*/public static void uploadFileToSharedFolder(String remoteUrl, String shareFolderPath, String localFilePath, String fileName) {InputStream inputStream = null;OutputStream outputStream = null;try {File localFile = new File(localFilePath);inputStream = new FileInputStream(localFile);// smb://userName:passWord@host/path/shareFolderPath/fileNameSmbFile smbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);smbFile.connect();outputStream = new SmbFileOutputStream(smbFile);byte[] buffer = new byte[4096];int len = 0; // 读取长度while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {outputStream.write(buffer, 0, len);}// 刷新缓冲的输出流outputStream.flush();} catch (FileNotFoundException e) {e.printStackTrace();throw new RRException(e.getMessage());} catch (MalformedURLException e) {e.printStackTrace();throw new RRException(e.getMessage());} catch (IOException e) {e.printStackTrace();throw new RRException(e.getMessage());} finally {try {outputStream.close();inputStream.close();} catch (IOException e) {e.printStackTrace();throw new RRException(e.getMessage());}}}/*** 上传文件* @param remoteUrl* @param shareFolderPath* @param fileInputStream* @param fileName*/public static void uploadFileToSharedFolder(String remoteUrl, String shareFolderPath, InputStream inputStream, String fileName) {OutputStream outputStream = null;try {// smb://userName:passWord@host/path/shareFolderPath/fileNameSmbFile smbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);smbFile.connect();outputStream = new SmbFileOutputStream(smbFile);byte[] buffer = new byte[4096];int len = 0; // 读取长度while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {outputStream.write(buffer, 0, len);}// 刷新缓冲的输出流outputStream.flush();} catch (FileNotFoundException e) {e.printStackTrace();throw new RRException(e.getMessage());} catch (MalformedURLException e) {e.printStackTrace();throw new RRException(e.getMessage());} catch (IOException e) {e.printStackTrace();throw new RRException(e.getMessage());} finally {try {outputStream.close();inputStream.close();} catch (IOException e) {e.printStackTrace();throw new RRException(e.getMessage());}}}/*** 下载文件到浏览器* @param httpServletResponse* @param remoteUrl* @param shareFolderPath* @param fileName*/public static void downloadFileToBrowser(HttpServletResponse httpServletResponse, String remoteUrl, String shareFolderPath, String fileName) {SmbFile smbFile;SmbFileInputStream smbFileInputStream = null;OutputStream outputStream = null;try {// smb://userName:passWord@host/path/shareFolderPath/fileNamesmbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);smbFileInputStream = new SmbFileInputStream(smbFile);httpServletResponse.setHeader("content-type", "application/octet-stream");httpServletResponse.setContentType("application/vnd.ms-excel;charset=UTF-8");httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + fileName);// 处理空格转为加号的问题httpServletResponse.setHeader("Content-Disposition", "attachment; fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20"));outputStream = httpServletResponse.getOutputStream();byte[] buff = new byte[2048];int len;while ((len = smbFileInputStream.read(buff)) != -1) {outputStream.write(buff, 0, len);}} catch (MalformedURLException e) {e.printStackTrace();} catch (SmbException e) {e.printStackTrace();} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {try {outputStream.close();smbFileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}/*** 下载文件到指定文件夹* @param remoteUrl* @param shareFolderPath* @param fileName* @param localDir*/public static void downloadFileToFolder(String remoteUrl, String shareFolderPath, String fileName, String localDir) {InputStream in = null;OutputStream out = null;try {SmbFile remoteFile = new SmbFile(remoteUrl + shareFolderPath + File.separator + fileName);File localFile = new File(localDir + File.separator + fileName);in = new BufferedInputStream(new SmbFileInputStream(remoteFile));out = new BufferedOutputStream(new FileOutputStream(localFile));byte[] buffer = new byte[1024];while (in.read(buffer) != -1) {out.write(buffer);buffer = new byte[1024];}} catch (Exception e) {e.printStackTrace();} finally {try {out.close();in.close();} catch (IOException e) {e.printStackTrace();}}}/*** 删除文件* @param remoteUrl* @param shareFolderPath* @param fileName*/public static void deleteFile(String remoteUrl, String shareFolderPath, String fileName) {SmbFile SmbFile;try {// smb://userName:passWord@host/path/shareFolderPath/fileNameSmbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);if (SmbFile.exists()) {SmbFile.delete();}} catch (MalformedURLException e) {e.printStackTrace();} catch (SmbException e) {e.printStackTrace();}}// (这个方法可以适用比较老版本的windows系统的共享文件夹)public static void checkConnect(String host,String username,String password,String remoteUrl) {try {// smb://userName:passWord@host/path/shareFolderPath/fileNameString url="smb://"+host+remoteUrl;NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", username, password);SmbFile smbFile = new SmbFile(url,auth);System.out.println("smburl="+url);SmbFile[] files = smbFile.listFiles();for (SmbFile f : files) {System.out.println(f.getName());}} catch (MalformedURLException e) {e.printStackTrace();throw new RRException(e.getMessage());} catch (SmbException e) {e.printStackTrace();throw new RRException(e.getMessage());}}/*** @Description 上传文件到nas文件夹 (这个方法可以适用比较老版本的windows系统的共享文件夹)* @Author chengweiping* @Date 2021/7/23 12:22*/public static void uploadFileToSharedFolder(String host,String dir,String fileName,String username,String password,InputStream inputStream) {OutputStream outputStream = null;try {// smb://userName:passWord@host/path/shareFolderPath/fileName// SmbFile smbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);System.out.println("host:"+host+";password:"+password+";dir:"+dir+"fileName:"+fileName);String url="smb://"+host+dir;String fileNameUrl=url+fileName;System.out.println("url:"+url);System.out.println("fileNameUrl:"+fileNameUrl);NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", username, password);SmbFile smbFile = new SmbFile(fileNameUrl,auth);outputStream = new SmbFileOutputStream(smbFile);byte[] buffer = new byte[4096];int len = 0; // 读取长度while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {outputStream.write(buffer, 0, len);}// 刷新缓冲的输出流outputStream.flush();} catch (FileNotFoundException e) {e.printStackTrace();throw new RRException(e.getMessage());} catch (MalformedURLException e) {e.printStackTrace();throw new RRException(e.getMessage());} catch (IOException e) {e.printStackTrace();throw new RRException(e.getMessage());} finally {try {if(outputStream!=null){outputStream.close();}if(inputStream!=null){inputStream.close();}} catch (IOException e) {e.printStackTrace();throw new RRException(e.getMessage());}}}// smb://Getech:6661262@10.88.40.102/poc_202105private static final String SMB_SHARE_FOLDER = "smb://Getech:6661262@10.88.40.225:80/poc_202105/";private static final String SHARE_FOLDER_PATH = "/dip_data_service";private static final String FILE_NAME = "test3.txt";private static final String LOCAL_DIR = "D:\\LocalTest\\test.txt";public static void main(String[] args) {//uploadFileToSharedFolder(SMB_SHARE_FOLDER,SHARE_FOLDER_PATH,LOCAL_DIR,FILE_NAME);// getSharedFileList(SMB_SHARE_FOLDER+SHARE_FOLDER_PATH+"/");String host= "10.88.40.225";String remoteDir= "/poc_202105/";String username="getech";String password="6661262";String port= "80";System.out.println("host:="+host+";port:"+port+",username:"+username+",password="+password+",dir="+remoteDir);checkConnect(host,username,password,remoteDir);}}
参考文章链接:
Java中SMB的应用_终极冥帝-CSDN博客_java smb
rancher搭建samda服务教程
CSDNhttps://mp.csdn.net/mp_blog/creation/editor/12211095
通过smb协议上传下载文件到nas相关推荐
- 易语言客户端请求http_易语言通过Http协议上传下载文件
易语言通过Http协议上传下载文件 2018-11-29 .版本 2 .程序集 窗口程序集1 .程序集变量 程序集_数据, 字节集 .子程序 _按钮1_被单击 信息框 (客户1.连接 ("b ...
- 初级版python登录验证,上传下载文件加MD5文件校验
服务器端程序 import socket import json import struct import hashlib import osdef md5_code(usr, pwd):ret = ...
- SecureCRT上传下载文件
2019独角兽企业重金招聘Python工程师标准>>> SecureCRT是一个仿真终端连接工具.它可以方便的连接SSH服务器,远程管理Linux.同时,它还能使用多种协议方便的上传 ...
- 上传下载文件到Linux服务器
转自链接:https://blog.csdn.net/drdongshiye/article/details/89430535 Mac的终端是十分强大 , 可以通过命令进行上传下载 下载文件夹 scp ...
- go ssh 执行多个命令_Gox语言中通过SSH远程执行命令及上传下载文件-GX10
Gox语言作为一个"粘合剂"语言,当然需要有便捷的网络编程能力和远程服务器操作的能力,没有让人失望的是,这确实也正是它所擅长的. 再次说明,Gox语言的安装很简单,只需要去官网下载 ...
- SecureCRTSecureFX Portable远程连接Linux;上传下载文件
SecureCRT和SecureFX都是由VanDyke出品的SSH传输工具. SecureCRT是一款非常好用的.支持多标签的SSH客户端,极大方便了管理多个SSH会话. SecureFX则是一款专 ...
- springboot上传下载文件(4)--上传下载工具类(已封装)
因为在做毕设,发现之前的搭建ftp文件服务器,通过ftp协议无法操作虚拟机临时文件,又因为ftp文件服务器搭建的比较麻烦:而 hadoop的HDFS虽然可以实现,但我这里用不到那么复杂的:所以我封装了 ...
- Linux| 向linux服务器上传下载文件方式收集(scp)
scp [优点]简单方便,安全可靠:支持限速参数 [缺点]不支持排除目录 [用法] scp就是secure copy,是用来进行远程文件拷贝的.数据传输使用 ssh,并且和ssh 使用相同的认证方式, ...
- secure CRT上传下载文件
SecureCRT这款SSH客户端软件同时具备了终端仿真器和文件传输功能.比ftp命令方便多了,而且服务器不用再开FTP服务了.rz,sz是便是Linux/Unix同Windows进行ZModem文件 ...
最新文章
- HTTP访问服务的相关解释
- 拆分字符串的表值函数
- 八大排序算法图文讲解
- 概述--Nginx集成Vcenter 6.X HTML Console系列之 1--(共4)
- leetcode python3 简单题28. Implement strStr()
- hbase1.3版本启动流程及优化
- 环评师考各个科目有哪些备考的好方法?
- 暴力裁员绝症员工,网易刚刚道歉!丁磊沉默,刘强东意外刷屏:说了这句硬气的话……
- 20个BT下载网站,BT种子网站
- DFS判断回路及回路个数
- 81章 老子1章到_《道德经》81章全文,建议全文背诵,终身体悟
- 应用宝shangjia安全评估报告_【开发者必看】APP《安全评估报告》怎么写?附填写范例...
- Python实现图片黑白化
- linux查找所有可用的摄像头
- centos7 nvidia显卡安装
- 微软官网服务器dns,域名系统 (DNS)
- 这五个资源网站真的是非常强大 请尽快收藏
- 《漫步华尔街》摘抄与读后感
- redis客户端predis介绍
- 美国在线黄页服务提供商YP控股拟竞购雅虎网络资产
热门文章
- PP66 EEPPPPMM SSyysstteemm AAddmmiinniissttrraattiioonn GGuuiiddee 16 R1
- crm智能化加持企业售后服务
- 中水处理设备:工业中水回用设备技术应用
- 独家一比一精仿火萤动态壁纸全套微信小程序源码下载-支持动静态和头像
- SwinTransformer:使用shifted window的层级Transformer(ICCV2021)
- java mcu 视频会议_视频会议终端和MCU两者有什么区别
- html基础标签-1-pre预格式标签
- 将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 类似于图中效果
- html单选按钮样式 正方形,Html单选按钮自定义样式
- “小程序化”,一种创新的混合App开发模式