前提:

(1)在文件服务器共享文件夹,设置权限(特定某个用户可以访问)。

(2)配置WEB-INF/classess/ftp.properties文件。

<span style="color:#333333;">//1 FTP , 2 FileSystem ,3 smb upload
file.upload.type=3#FTP server
ftp.ip=172.16.5.158
ftp.port=21
ftp.username=jc
ftp.password=123456
ftp.url=/jmykt/file/ftp.jsp?f=#File upload
upload.path=d\:\\temp
upload.url=/tbsm-web/file/res.jsp?f=#smb upload
#smb.upload.path=smb://test:123@192.168.20.32/temp/
smb.upload.path=smb://Administrator:trustel@192.168.200.160/tbsmSmb/
smb.upload.url=/mytest/file/smb.jsp?f=

注释:smb.upload.path是文件上传路径,格式是smb://用户名:密码@IP/共享文件夹名称/

smb.upload.url是显示的时候用到,比如图片显示。

(3)导入Jar包jcifs-1.3.16.jar。

一、上传文件

(1)JSP页面上传:
<form action="<%=request.getContextPath() %>/good/smbUploadFile.action" name="form1" method="post"  theme="simple" enctype="multipart/form-data" >SMB上传文件:<input type="file" name="upload" size="30"/><input type="submit" value="上 传" />
</form>
(2)Action:
// 基于SMB协议的文件上传;
private File upload;
private String uploadContentType;
private String uploadFileName;
public File getUpload() {return upload;}public void setUpload(File upload) {this.upload = upload;}public String getUploadContentType() {return uploadContentType;}public void setUploadContentType(String uploadContentType) {this.uploadContentType = uploadContentType;}public String getUploadFileName() {return uploadFileName;}public void setUploadFileName(String uploadFileName) {this.uploadFileName = uploadFileName;}
public String smbUploadFile() {HttpServletRequest request=ServletActionContext.getRequest();try {if(uploadFileName!=null&&!uploadFileName.equals("")){String fileUrl=FileUploadFactory.getFileUpload().upload(upload,"pic", uploadFileName);request.setAttribute("fileUrl", fileUrl);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return SUCCESS;}
(3)业务代码:
FileUploadFactory.java
package com.trustel.common.file;import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;public class FileUploadFactory {static String CONFIG_FILE_NAME = "/ftp.properties";/*** 获得文件上传的对象* @return* @throws IOException */public static IFileUpload getFileUpload() throws IOException{InputStream in = FileUploadFactory.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);if (in == null){in = FileUploadFactory.class.getClass().getResourceAsStream(CONFIG_FILE_NAME);}Properties p = new Properties();p.load(in);int FILE_UPLOAD_TYPE = Integer.parseInt(p.getProperty("file.upload.type").trim());IFileUpload upload = null;switch (FILE_UPLOAD_TYPE) {case IFileUpload.FILE_UPLOAD_TYPE_FTP://upload = new FTPFileUpload();break;case IFileUpload.FILE_UPLOAD_TYPE_FILE://upload = new LocalFileUpload();break;case IFileUpload.FILE_UPLOAD_TYPE_SMB:upload = new SMBFileUpload();break;}upload.setProperties(p);return upload;}/*** 获取显示URL路径;* @return* @throws IOException*/public static String getUploadURL() throws IOException{InputStream in = FileUploadFactory.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);if (in == null){in = FileUploadFactory.class.getClass().getResourceAsStream(CONFIG_FILE_NAME);}Properties p = new Properties();p.load(in);   int FILE_UPLOAD_TYPE = Integer.parseInt(p.getProperty("file.upload.type").trim());if(FILE_UPLOAD_TYPE==3){return p.getProperty("smb.upload.url").trim(); }else{return p.getProperty("upload.url").trim();  }}/*** 获取上传远程服务器的路径;* @return* @throws IOException*/public static String getUploadPath() throws IOException{InputStream in = FileUploadFactory.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);if (in == null){in = FileUploadFactory.class.getClass().getResourceAsStream(CONFIG_FILE_NAME);}Properties p = new Properties();p.load(in);    int FILE_UPLOAD_TYPE = Integer.parseInt(p.getProperty("file.upload.type").trim());if(FILE_UPLOAD_TYPE==3){return p.getProperty("smb.upload.path").trim();    }else{return p.getProperty("upload.path").trim(); }}
}

SMBFileUpload.java

package com.trustel.common.file;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;/*** 通过网络共享的方式上传文件* @author cai_zr**/
public class SMBFileUpload implements IFileUpload{private String smb_upload_path;private String smb_upload_url; private final static String sysSeparator = System.getProperty("file.separator");public static String FILE_PATH = "tbsm"+sysSeparator+"tbsmfile";public SMBFileUpload(){}public void setProperties(Properties p) {smb_upload_path = p.getProperty("smb.upload.path").trim();smb_upload_url = p.getProperty("smb.upload.url").trim();}public String upload(File file,String filePath, String fileName) {//创建目录        SimpleDateFormat sim=new SimpleDateFormat("yyyyMM");String path=sim.format(new Date()) + "/";String folder=FILE_PATH+sysSeparator+filePath;if (!folder.endsWith("\\")) {folder += "\\";}if ("\\".equals(sysSeparator)) {folder = folder.replace("/", "\\");}folder=folder.replace("\\", "//");String remoteUrl = smb_upload_path + folder;try {System.out.println("remoteUrl:"+remoteUrl);  SmbFile remoteFile1 = new SmbFile(remoteUrl);if (!remoteFile1.exists()) remoteFile1.mkdirs();remoteFile1 = null;} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();return null;}//上传文件InputStream in = null;    OutputStream out = null;    SmbFile remoteFile = null;try {    File localFile = file;  SimpleDateFormat sim1=new SimpleDateFormat("yyMMddHHmmssSSS");//上传后的文件名String newFileName=sim1.format(new Date())+"."+fileName.split("\\.")[1];remoteFile = new SmbFile(remoteUrl+sysSeparator+newFileName);    in = new BufferedInputStream(new FileInputStream(localFile));    out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));    byte[] buffer = new byte[1024];    while (in.read(buffer) != -1) {    out.write(buffer);    buffer = new byte[1024];    }    //System.out.println("SMB Upload:" + localFile.getPath() + " => " + remoteUrl + newFileName);return filePath+sysSeparator+newFileName;} catch (Exception e) {    e.printStackTrace();    } finally {    try {    out.close();    in.close(); remoteFile = null;} catch (IOException e) {    e.printStackTrace();    }    }  return null;}
}

IFileUpload.java

package com.trustel.common.file;import java.io.File;
import java.util.Properties;public interface IFileUpload {//文件上传的方式 ,1FTP,2普通文件上传,3共享上传public static int FILE_UPLOAD_TYPE_FTP = 1;  public static int FILE_UPLOAD_TYPE_FILE = 2;public static int FILE_UPLOAD_TYPE_SMB = 3;/*** 设置配置信息* @param p*/public void setProperties(Properties p);/*** 上传文件,并返回上传文件的URL* @return*/public String upload(File file,String folder,String fileName);}

(4) JSP页面显示图片:

<%String fileUrl=(String)request.getAttribute("fileUrl");String FILE_PATH = "tbsm/tbsmfile";if(fileUrl!=null&&!fileUrl.equals("")){%><img src="<%=FileUploadFactory.getUploadURL() %>/<%=FILE_PATH %>/<%=fileUrl %>" /><%} %>

注释:src路径根据ftp.properties文件中的 smb.upload.url路径读取对应的JSP显示图片。

smb.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@page import="java.io.OutputStream"%>
<%@page import="jcifs.smb.SmbFile"%>
<%@page import="jcifs.smb.SmbFileInputStream"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="com.trustel.common.file.FileUploadFactory"%>
<%
String path = request.getContextPath();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");String FILE_PRE = FileUploadFactory.getUploadPath();//"smb://smb_user:123456@192.168.132.20/test_smb/";
String filePath = request.getParameter("f");
if (filePath == null) {out.print("can't find resource!");return ;
}
String ext = filePath.substring(filePath.lastIndexOf(".")+1);//读取文件扩展名
ext = ext.toLowerCase();String contentType = "";
if (ext.equals("gif")){contentType = "image/GIF";
}else if (ext.equals("jpg")){contentType = "image/JPEG";
}else if (ext.equals("jpeg")){contentType = "image/JPEG";
}else if (ext.equals("png")){contentType = "image/PNG";
}else if (ext.equals("txt")){contentType = "application/octet-stream";String fileName = filePath.substring(filePath.lastIndexOf("//")+2);response.setHeader("Content-Disposition","attachment;filename="+fileName);
}else{
contentType = "application/octet-stream";String fileName = filePath.substring(filePath.lastIndexOf("//")+2);response.setHeader("Content-Disposition","attachment;filename="+fileName);}
/*
if (contentType.length()==0){out.print("can't find resource!");return ;
}*///System.out.println(contentType);
SmbFileInputStream in = null;
OutputStream out1 = null;
out.clear();
try{SmbFile smbFile = new SmbFile(FILE_PRE + filePath);   System.out.println("load:"+ smbFile.getPath()); int length = smbFile.getContentLength();// 得到文件的大小    byte buffer[] = new byte[length];    in = new SmbFileInputStream(smbFile);   out1 = response.getOutputStream();response.setContentType(contentType); int len =0;byte[] bytes = new byte[1024];//System.out.println("============"); while( (len=in.read(bytes)) > 0){out1.write(bytes,0,len);//System.out.println("=="+len);}//out1.flush();out1.close();response.flushBuffer();//在tomcat下加上下面两句才不会出现错误: Servlet.service() for servlet jsp threw exceptionout.clear();out = pageContext.pushBody();
}catch(Exception e){out.print("load resouce error. ");e.printStackTrace();
}finally{if(in != null) in.close();//if(out1 !=null) out1.close();
}
%>

二、下载文件

(1)手动保存文件:
  JSP页面:
SMB下载文件:<a href="<%=request.getContextPath() %>/good/handDownLoadFile.action">手动保存</a>

Action:

       /*** SMB下载文件 手动保存;* @return* @throws IOException */public String handDownLoadFile() throws IOException{//数据库中存入的文件路径;String fileURL="pic/140509092233296.jpeg";String path=FileUploadFactory.getUploadPath()+"tbsm/tbsmfile/"+fileURL;ServletActionContext.getRequest().setAttribute("filePath",path);ServletActionContext.getRequest().setAttribute("fileName",fileURL.substring(fileURL.lastIndexOf("/")+1));return SUCCESS;}

download.jsp:

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page language="java" import="java.util.*,java.io.*" %>
<%@page import="jcifs.smb.SmbFile"%>
<%@page import="jcifs.smb.SmbFileInputStream"%><%String filePath="";String fileName="";if(request.getAttribute("filePath")!=null && !request.getAttribute("filePath").equals("")){filePath=request.getAttribute("filePath").toString();fileName=request.getAttribute("fileName").toString();String realPath = filePath;SmbFileInputStream in = null;OutputStream os = null;try {//java.io.File file=new java.io.File(realPath);SmbFile file = new SmbFile(realPath);     if(!file.exists()) {out.println("下载的文件不存在!");return;}   out.clear();response.setContentType("application/x-msdownload");response.setHeader("Content-disposition","attachment; filename="+new String(fileName.getBytes(),"ISO8859_1"));   in = new SmbFileInputStream(file); DataInputStream dis=new DataInputStream(in); os = response.getOutputStream();byte[] buf=new byte[1024];int left=(int)file.length();   int read=0;   while(left>0) {read=dis.read(buf);   left-=read;   os.write(buf,0,read);   }   if (true) {return;}  } catch (Exception e) {e.printStackTrace();} finally {      if (in != null) {in.close();  }if (os != null) {os.close();  } }}else{%><script type="text/javascript">history.go(-1);   window.alert('没有附件,不能下载')</script><%}
%>

注释:JSP页面发送请求,Struts找到对应的Action方法,处理完毕后放回String,跳转download.jsp。

(2)自动保存文件:

JSP页面:
SMB下载文件:<a href="<%=request.getContextPath() %>/good/autoDownLoadFile.action">自动保存</a>

Action:

       /*** SMB下载文件 自动保存;* @return* @throws IOException */public String autoDownLoadFile() throws IOException{//数据库中存入的文件路径;String fileURL="pic/140509092233296.jpeg";String filePath="D://WebApplication/tbsm/tbsmfile/"+fileURL;File file=new File(filePath);//如果文件路径的文件夹不存在,需要创建。String smbPath = FileUploadFactory.getUploadPath(); smbPath+="tbsm/tbsmfile/"+fileURL;SmbFileInputStream in = null;FileOutputStream os = null;SmbFile smbFile = new SmbFile(smbPath);int length = smbFile.getContentLength();// 得到文件的大小    byte buffer[] = new byte[length];    in = new SmbFileInputStream(smbFile);   os = new FileOutputStream(file);int len =0;byte[] bytes = new byte[1024];while( (len=in.read(bytes)) > 0){os.write(bytes,0,len);}os.close();in.close();return SUCCESS;}

这是工程中的应用,简单的例子可以参考http://dongisland.iteye.com/blog/1453613

SMB实现共享文件(上传、下载)相关推荐

  1. JCIFS简介and利用JCIFS网络文件共享实现上传下载

    JCIFS简介and利用JCIFS网络文件共享实现上传下载 JCIFS is an Open Source client library that implements the CIFS/SMB ne ...

  2. 文件服务器 上传 下载

    什么是文件服务器?文件服务器因为名称是File server,又称为档案伺服器,是网络设备中专门用于存储访问文件的设备,是一种专供其他电脑检索文件和存储的特殊电脑. 其实文件服务器就和我们常说的网盘一 ...

  3. ubuntu下搭建FTP服务器并使用FileZilla上传下载

    ubuntu下搭建FTP服务器并使用FileZilla上传下载 为了让实验室同学在共享文件时更加方便,我们决定在实验室电脑上搭建一个FTP服务器,ubuntu系统版本为16.04,下面就是我的搭建流程 ...

  4. Box浅度接触-Java实现Box文件上传下载

    背景 Box(https://www.box.com/home)是定义为内容云,在我有限认知里面,感觉应该和云存储系统没啥区别.近日,有幸和Box做了一次浅度接触,颇为缠绵,记录在这里供有需要的朋友参 ...

  5. 初级版python登录验证,上传下载文件加MD5文件校验

    服务器端程序 import socket import json import struct import hashlib import osdef md5_code(usr, pwd):ret = ...

  6. linux快捷上传下载文件

    借助securtCRT,使用linux命令sz可以很方便的将服务器上的文件下载到本地,使用rz命令则是把本地文件上传到服务器 其中,对于sz和rz的理解与记忆我用了如下的方法(因为很多时候容易搞混): ...

  7. Java中使用FTPClient上传下载

    转自:http://blog.csdn.net/hbcui1984/article/details/2720204 在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文 ...

  8. JSP中的文件操作:数据流、File类、文件浏览、目录操作、上传下载

    ​ 文件可以永久地存储信息,从本质上讲文件就是存放在盘上的一系列数据的集合.应用程序如果想长期保存数据,就必须将数据存储到文件中,这就涉及到文件的操作.而在编写网站应用程序的过程中,有许多地方要对文件 ...

  9. 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 作者:宇的季节 cnblogs.com/chenkeyu/p/80 ...

  10. 教你如何实现c#文件上传下载功能

    简单介绍一下c#文件上传下载功能实现. NuGet 安装SqlSugar Model文件下新建 DbContext 类 public class DbContext {public DbContext ...

最新文章

  1. 085_html5服务器发送事件
  2. 输入5个整形数据_妙招技法:Excel表格数据录入的5个小技巧
  3. (转)超全面设计指南:如何做大屏数据可视化设计?
  4. List集合中对象的排序
  5. 配置防盗链 访问控制Directory 访问控制FilesMatch
  6. 设计模式C++实现--Factory模式
  7. Undo log日志详解
  8. 整人代码好玩到没朋友
  9. Mac电脑快速查找文件的两种方法
  10. 转:: 刺鸟:用python来开发webgame服务端(5)
  11. 今天过节,摔杯,逼宫,吃瓜吧?
  12. 曾经社交王者人人为何如今失魂落魄
  13. (23) 基于深度学习框架的出租车OD需求预测应用对比
  14. 在Linux中安装MySQL报错“error: Failed dependencies: mysql-community-libs(x86-32) >= 5.7.9 is needed by my“
  15. torch.squeeze和torch.unsqueeze
  16. python 字符串长度
  17. 软件测试初级测试之测试基础
  18. 计算机技术在环境工程中有哪些应用,计算机在环境工程中的应用技术
  19. 教你一招解决Win10计算器打不开的问题
  20. python蟒蛇绘制实例分析_2.4蟒蛇绘制程序分析

热门文章

  1. Java实现emf转jpg png 图片转换
  2. 安然邮箱社交网络分析
  3. python画结节图像_天池医疗AI大赛[第一季]:肺部结节U-Net图像分割
  4. Identifier ‘XX‘ has already been declared
  5. 三维点云数据处理软件供技术原理说明_基于三维点云处理技术的工件识别和匹配...
  6. 为魅族M8手机开发的围棋打谱软件(M8WeiqiPu)发布0.8版,多图
  7. arcgis售价_售价70美元的视频游戏的看不见的含义
  8. Mac 自带ftp命令
  9. root程序拆卸,把root软件删了
  10. 程序员常见的口头禅,哈哈哈哈~