前提:
(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.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 block
- e.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();
- }
- }
- }
- 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 block
- e1.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;
- }
- }
- 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);
- }
- <%
- String fileUrl=(String)request.getAttribute("fileUrl");
- String FILE_PATH = "tbsm/tbsmfile";
- if(fileUrl!=null&&!fileUrl.equals("")){
- %>
- <img src="<%=FileUploadFactory.getUploadURL() %>/<%=FILE_PATH %>/<%=fileUrl %>" />
- <%} %>
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 exception
- out.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>
- /**
- * 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;
- }
- <%@ 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>
- <%}
- %>
(2)自动保存文件:
JSP页面:
- SMB下载文件:<a href="<%=request.getContextPath() %>/good/autoDownLoadFile.action">自动保存</a>
- /**
- * SMB下载文件 自动保存;
- * @return
- * @throws IOException
- */
- ublic 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