SMB实现共享文件(上传、下载)

点击打开链接

前提:

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

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

[html]  view plain  copy
  1. <span style="color:#333333;">//1 FTP , 2 FileSystem ,3 smb upload  
  2. file.upload.type=3  
  3.   
  4. #FTP server   
  5. ftp.ip=172.16.5.158  
  6. ftp.port=21  
  7. ftp.username=jc  
  8. ftp.password=123456  
  9. ftp.url=/jmykt/file/ftp.jsp?f=  
  10.   
  11. #File upload   
  12. upload.path=d\:\\temp  
  13. upload.url=/tbsm-web/file/res.jsp?f=  
  14.   
  15. #smb upload   
  16. #smb.upload.path=smb://test:123@192.168.20.32/temp/  
  17. smb.upload.path=smb://Administrator:trustel@192.168.200.160/tbsmSmb/  
  18. 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页面上传:
[html]  view plain  copy
  1. <form action="<%=request.getContextPath() %>/good/smbUploadFile.action" name="form1" method="post"  theme="simple" enctype="multipart/form-data" >  
  2.        SMB上传文件:<input type="file" name="upload" size="30"/><input type="submit" value="上 传" />  
  3. </form>  
 
(2)Action:
[html]  view plain  copy
  1. // 基于SMB协议的文件上传;  
  2. private File upload;  
  3. private String uploadContentType;  
  4. private String uploadFileName;  
  5. public File getUpload() {  
  6.         return upload;  
  7.     }  
  8.   
  9.     public void setUpload(File upload) {  
  10.         this.upload = upload;  
  11.     }  
  12.   
  13.     public String getUploadContentType() {  
  14.         return uploadContentType;  
  15.     }  
  16.   
  17.     public void setUploadContentType(String uploadContentType) {  
  18.         this.uploadContentType = uploadContentType;  
  19.     }  
  20.   
  21.     public String getUploadFileName() {  
  22.         return uploadFileName;  
  23.     }  
  24.   
  25.     public void setUploadFileName(String uploadFileName) {  
  26.         this.uploadFileName = uploadFileName;  
  27.     }  
  28. public String smbUploadFile() {  
  29.         HttpServletRequest request=ServletActionContext.getRequest();  
  30.         try {  
  31.           if(uploadFileName!=null&&!uploadFileName.equals("")){  
  32.             String fileUrl=FileUploadFactory.getFileUpload().upload(upload,"pic", uploadFileName);  
  33.             request.setAttribute("fileUrl", fileUrl);  
  34.           }  
  35.             
  36.         } catch (Exception e) {  
  37.             // TODO Auto-generated catch block  
  38.             e.printStackTrace();  
  39.         }  
  40.         return SUCCESS;  
  41.     }  



 (3)业务代码: 
FileUploadFactory.java
[html]  view plain  copy
  1. package com.trustel.common.file;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.Properties;  
  6.   
  7. public class FileUploadFactory {  
  8.       
  9.     static String CONFIG_FILE_NAME = "/ftp.properties";  
  10.       
  11.     /**  
  12.      * 获得文件上传的对象  
  13.      * @return  
  14.      * @throws IOException   
  15.      */  
  16.     public static IFileUpload getFileUpload() throws IOException{  
  17.         InputStream in = FileUploadFactory.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);  
  18.         if (in == null){  
  19.             in = FileUploadFactory.class.getClass().getResourceAsStream(CONFIG_FILE_NAME);  
  20.         }  
  21.         Properties p = new Properties();  
  22.         p.load(in);  
  23.         int FILE_UPLOAD_TYPE = Integer.parseInt(p.getProperty("file.upload.type").trim());  
  24.         IFileUpload upload = null;  
  25.         switch (FILE_UPLOAD_TYPE) {  
  26.             case IFileUpload.FILE_UPLOAD_TYPE_FTP:  
  27.                 //upload = new FTPFileUpload();  
  28.                 break;  
  29.   
  30.             case IFileUpload.FILE_UPLOAD_TYPE_FILE:  
  31.                 //upload = new LocalFileUpload();  
  32.                 break;  
  33.                   
  34.             case IFileUpload.FILE_UPLOAD_TYPE_SMB:  
  35.                 upload = new SMBFileUpload();  
  36.                 break;  
  37.         }  
  38.         upload.setProperties(p);  
  39.         return upload;  
  40.     }  
  41.       
  42.     /**  
  43.      * 获取显示URL路径;  
  44.      * @return  
  45.      * @throws IOException  
  46.      */  
  47.     public static String getUploadURL() throws IOException{  
  48.         InputStream in = FileUploadFactory.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);  
  49.         if (in == null){  
  50.             in = FileUploadFactory.class.getClass().getResourceAsStream(CONFIG_FILE_NAME);  
  51.         }  
  52.         Properties p = new Properties();  
  53.         p.load(in);   
  54.         int FILE_UPLOAD_TYPE = Integer.parseInt(p.getProperty("file.upload.type").trim());  
  55.         if(FILE_UPLOAD_TYPE==3){  
  56.           return p.getProperty("smb.upload.url").trim();      
  57.         }else{  
  58.           return p.getProperty("upload.url").trim();      
  59.         }  
  60.     }  
  61.     /**  
  62.      * 获取上传远程服务器的路径;  
  63.      * @return  
  64.      * @throws IOException  
  65.      */  
  66.     public static String getUploadPath() throws IOException{  
  67.         InputStream in = FileUploadFactory.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);  
  68.         if (in == null){  
  69.             in = FileUploadFactory.class.getClass().getResourceAsStream(CONFIG_FILE_NAME);  
  70.         }  
  71.         Properties p = new Properties();  
  72.         p.load(in);   
  73.         int FILE_UPLOAD_TYPE = Integer.parseInt(p.getProperty("file.upload.type").trim());  
  74.         if(FILE_UPLOAD_TYPE==3){  
  75.           return p.getProperty("smb.upload.path").trim();     
  76.         }else{  
  77.           return p.getProperty("upload.path").trim();     
  78.         }  
  79.     }  
  80. }  
SMBFileUpload.java
[html]  view plain  copy
  1. package com.trustel.common.file;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10. import java.text.SimpleDateFormat;  
  11. import java.util.Date;  
  12. import java.util.Properties;  
  13. import jcifs.smb.SmbFile;  
  14. import jcifs.smb.SmbFileOutputStream;  
  15.   
  16. /**  
  17.  * 通过网络共享的方式上传文件  
  18.  * @author cai_zr  
  19.  *  
  20.  */  
  21. public class SMBFileUpload implements IFileUpload{  
  22.     private String smb_upload_path;  
  23.     private String smb_upload_url;    
  24.       
  25.     private final static String sysSeparator = System.getProperty("file.separator");  
  26.     public static String FILE_PATH = "tbsm"+sysSeparator+"tbsmfile";  
  27.       
  28.     public SMBFileUpload(){}  
  29.       
  30.     public void setProperties(Properties p) {  
  31.         smb_upload_path = p.getProperty("smb.upload.path").trim();  
  32.         smb_upload_url = p.getProperty("smb.upload.url").trim();  
  33.     }  
  34.   
  35.     public String upload(File file,String filePath, String fileName) {  
  36.     //创建目录        
  37.         SimpleDateFormat sim=new SimpleDateFormat("yyyyMM");  
  38.     String path=sim.format(new Date()) + "/";  
  39.     String folder=FILE_PATH+sysSeparator+filePath;  
  40.           
  41.     if (!folder.endsWith("\\")) {  
  42.       folder += "\\";  
  43.     }  
  44.     if ("\\".equals(sysSeparator)) {  
  45.       folder = folder.replace("/", "\\");  
  46.     }  
  47.     folder=folder.replace("\\", "//");  
  48.     String remoteUrl = smb_upload_path + folder;  
  49.     try {  
  50.       System.out.println("remoteUrl:"+remoteUrl);    
  51.       SmbFile remoteFile1 = new SmbFile(remoteUrl);  
  52.       if (!remoteFile1.exists()) remoteFile1.mkdirs();  
  53.       remoteFile1 = null;  
  54.     } catch (Exception e1) {  
  55.       // TODO Auto-generated catch block  
  56.       e1.printStackTrace();  
  57.       return null;  
  58.     }  
  59.           
  60.     //上传文件  
  61.         InputStream in = null;      
  62.         OutputStream out = null;      
  63.         SmbFile remoteFile = null;  
  64.         try {      
  65.             File localFile = file;    
  66.             SimpleDateFormat sim1=new SimpleDateFormat("yyMMddHHmmssSSS");  
  67.             //上传后的文件名  
  68.            String newFileName=sim1.format(new Date())+"."+fileName.split("\\.")[1];  
  69.               
  70.             remoteFile = new SmbFile(remoteUrl+sysSeparator+newFileName);      
  71.             in = new BufferedInputStream(new FileInputStream(localFile));      
  72.             out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));      
  73.             byte[] buffer = new byte[1024];      
  74.             while (in.read(buffer) != -1) {      
  75.                 out.write(buffer);      
  76.                 buffer = new byte[1024];      
  77.             }      
  78.             //System.out.println("SMB Upload:" + localFile.getPath() + " => " + remoteUrl + newFileName);  
  79.             return filePath+sysSeparator+newFileName;  
  80.         } catch (Exception e) {      
  81.             e.printStackTrace();      
  82.         } finally {      
  83.             try {      
  84.                 out.close();      
  85.                 in.close();   
  86.                 remoteFile = null;  
  87.             } catch (IOException e) {      
  88.                 e.printStackTrace();      
  89.             }      
  90.         }    
  91.         return null;  
  92.     }  
  93. }  
IFileUpload.java
[html]  view plain  copy
  1. package com.trustel.common.file;  
  2.   
  3. import java.io.File;  
  4. import java.util.Properties;  
  5.   
  6. public interface IFileUpload {  
  7.     //文件上传的方式 ,1FTP,2普通文件上传,3共享上传  
  8.     public static int FILE_UPLOAD_TYPE_FTP = 1;    
  9.     public static int FILE_UPLOAD_TYPE_FILE = 2;  
  10.     public static int FILE_UPLOAD_TYPE_SMB = 3;  
  11.       
  12.     /**  
  13.      * 设置配置信息  
  14.      * @param p  
  15.      */  
  16.     public void setProperties(Properties p);  
  17.     /**  
  18.      * 上传文件,并返回上传文件的URL  
  19.      * @return  
  20.      */  
  21.     public String upload(File file,String folder,String fileName);  
  22.       
  23. }  
(4) JSP页面显示图片:
[html]  view plain  copy
  1. <%  
  2.     String fileUrl=(String)request.getAttribute("fileUrl");  
  3.     String FILE_PATH = "tbsm/tbsmfile";  
  4.     if(fileUrl!=null&&!fileUrl.equals("")){  
  5.  %>  
  6.  <img src="<%=FileUploadFactory.getUploadURL() %>/<%=FILE_PATH %>/<%=fileUrl %>" />  
  7.  <%} %>  
注释:src路径根据ftp.properties文件中的 smb.upload.url路径读取对应的JSP显示图片。
smb.jsp:
[html]  view plain  copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>  
  2. <%@page import="java.io.OutputStream"%>  
  3. <%@page import="jcifs.smb.SmbFile"%>  
  4. <%@page import="jcifs.smb.SmbFileInputStream"%>  
  5. <%@page import="java.text.SimpleDateFormat"%>  
  6. <%@page import="com.trustel.common.file.FileUploadFactory"%>  
  7. <%  
  8. String path = request.getContextPath();  
  9. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  
  10.       
  11. String FILE_PRE = FileUploadFactory.getUploadPath();//"smb://smb_user:123456@192.168.132.20/test_smb/";   
  12. String filePath = request.getParameter("f");  
  13. if (filePath == null) {  
  14.   out.print("can't find resource!");  
  15.   return ;  
  16. }  
  17. String ext = filePath.substring(filePath.lastIndexOf(".")+1);//读取文件扩展名  
  18. ext = ext.toLowerCase();  
  19.   
  20. String contentType = "";  
  21. if (ext.equals("gif")){  
  22.     contentType = "image/GIF";  
  23. }else if (ext.equals("jpg")){  
  24.     contentType = "image/JPEG";  
  25. }else if (ext.equals("jpeg")){  
  26.     contentType = "image/JPEG";  
  27. }else if (ext.equals("png")){  
  28.     contentType = "image/PNG";  
  29. }else if (ext.equals("txt")){  
  30.     contentType = "application/octet-stream";  
  31.     String fileName = filePath.substring(filePath.lastIndexOf("//")+2);  
  32.     response.setHeader("Content-Disposition","attachment;filename="+fileName);  
  33. }else{  
  34. contentType = "application/octet-stream";  
  35.     String fileName = filePath.substring(filePath.lastIndexOf("//")+2);  
  36.     response.setHeader("Content-Disposition","attachment;filename="+fileName);  
  37.       
  38. }  
  39. /*  
  40. if (contentType.length()==0){  
  41.     out.print("can't find resource!");  
  42.     return ;  
  43. }*/  
  44.   
  45. //System.out.println(contentType);   
  46. SmbFileInputStream in = null;  
  47. OutputStream out1 = null;  
  48. out.clear();  
  49. try{  
  50.     SmbFile smbFile = new SmbFile(FILE_PRE + filePath);     
  51.     System.out.println("load:"+ smbFile.getPath());   
  52.     int length = smbFile.getContentLength();// 得到文件的大小      
  53.     byte buffer[] = new byte[length];      
  54.     in = new SmbFileInputStream(smbFile);     
  55.     out1 = response.getOutputStream();  
  56.     response.setContentType(contentType);   
  57.     int len =0;  
  58.     byte[] bytes = new byte[1024];  
  59.     //System.out.println("============");   
  60.     while( (len=in.read(bytes)) > 0){  
  61.         out1.write(bytes,0,len);  
  62.         //System.out.println("=="+len);  
  63.     }  
  64.       
  65.     //out1.flush();  
  66.     out1.close();  
  67.     response.flushBuffer();  
  68.     //在tomcat下加上下面两句才不会出现错误: Servlet.service() for servlet jsp threw exception  
  69.     out.clear();  
  70.     out = pageContext.pushBody();  
  71. }catch(Exception e){  
  72.     out.print("load resouce error. ");  
  73.     e.printStackTrace();  
  74. }finally{  
  75.     if(in != null) in.close();  
  76.     //if(out1 !=null) out1.close();  
  77. }  
  78. %>  

二、下载文件

(1)手动保存文件:
  JSP页面:
[html]  view plain  copy
  1. SMB下载文件:<a href="<%=request.getContextPath() %>/good/handDownLoadFile.action">手动保存</a>  
Action:
[html]  view plain  copy
  1.       /**  
  2.  * SMB下载文件 手动保存;  
  3.  * @return  
  4.  * @throws IOException   
  5.  */  
  6. public String handDownLoadFile() throws IOException{  
  7.   //数据库中存入的文件路径;  
  8.   String fileURL="pic/140509092233296.jpeg";  
  9.   String path=FileUploadFactory.getUploadPath()+"tbsm/tbsmfile/"+fileURL;  
  10.   ServletActionContext.getRequest().setAttribute("filePath",path);  
  11.   ServletActionContext.getRequest().setAttribute("fileName",fileURL.substring(fileURL.lastIndexOf("/")+1));  
  12.   return SUCCESS;  
  13. }  
download.jsp:
[html]  view plain  copy
  1. <%@ page contentType="text/html;charset=UTF-8" %>  
  2. <%@ page language="java" import="java.util.*,java.io.*" %>  
  3. <%@page import="jcifs.smb.SmbFile"%>  
  4. <%@page import="jcifs.smb.SmbFileInputStream"%>  
  5.       
  6. <%  
  7.     String filePath="";  
  8.     String fileName="";  
  9.     if(request.getAttribute("filePath")!=null && !request.getAttribute("filePath").equals("")){  
  10.         filePath=request.getAttribute("filePath").toString();  
  11.         fileName=request.getAttribute("fileName").toString();  
  12.         String realPath = filePath;  
  13.         SmbFileInputStream in = null;  
  14.         OutputStream os = null;  
  15.         try {  
  16.             //java.io.File file=new java.io.File(realPath);  
  17.             SmbFile file = new SmbFile(realPath);       
  18.             if(!file.exists()) {  
  19.                 out.println("下载的文件不存在!");  
  20.                 return;  
  21.             }     
  22.             out.clear();  
  23.             response.setContentType("application/x-msdownload");  
  24.             response.setHeader("Content-disposition","attachment; filename="+new String(fileName.getBytes(),"ISO8859_1"));     
  25.             in = new SmbFileInputStream(file);   
  26.             DataInputStream dis=new DataInputStream(in);   
  27.             os = response.getOutputStream();  
  28.             byte[] buf=new byte[1024];  
  29.             int left=(int)file.length();     
  30.             int read=0;     
  31.             while(left>0) {  
  32.                 read=dis.read(buf);     
  33.                 left-=read;     
  34.                 os.write(buf,0,read);     
  35.             }     
  36.             if (true) {  
  37.                 return;  
  38.             }    
  39.         } catch (Exception e) {  
  40.                 e.printStackTrace();  
  41.         } finally {       
  42.             if (in != null) {  
  43.                 in.close();    
  44.             }  
  45.             if (os != null) {  
  46.                 os.close();    
  47.             }   
  48.         }  
  49.     }else{  
  50.     %>  
  51.         <script type="text/javascript">  
  52.              history.go(-1);     
  53.             window.alert('没有附件,不能下载')  
  54.         </script>  
  55.     <%}  
  56. %>  
注释:JSP页面发送请求,Struts找到对应的Action方法,处理完毕后放回String,跳转download.jsp。

(2)自动保存文件:
JSP页面:
[html]  view plain  copy
  1. SMB下载文件:<a href="<%=request.getContextPath() %>/good/autoDownLoadFile.action">自动保存</a>  
Action:
[html]  view plain  copy
  1.      /**  
  2. * SMB下载文件 自动保存;  
  3. * @return  
  4. * @throws IOException   
  5. */  
  6. ublic String autoDownLoadFile() throws IOException{  
  7.   //数据库中存入的文件路径;  
  8.   String fileURL="pic/140509092233296.jpeg";  
  9.   String filePath="D://WebApplication/tbsm/tbsmfile/"+fileURL;  
  10.   File file=new File(filePath);//如果文件路径的文件夹不存在,需要创建。  
  11.     
  12.   String smbPath = FileUploadFactory.getUploadPath();   
  13.   smbPath+="tbsm/tbsmfile/"+fileURL;  
  14.   SmbFileInputStream in = null;  
  15.   FileOutputStream os = null;  
  16.   SmbFile smbFile = new SmbFile(smbPath);  
  17.   int length = smbFile.getContentLength();// 得到文件的大小      
  18.   byte buffer[] = new byte[length];      
  19.   in = new SmbFileInputStream(smbFile);     
  20.   os = new FileOutputStream(file);  
  21.   int len =0;  
  22.   byte[] bytes = new byte[1024];  
  23.   while( (len=in.read(bytes)) > 0){  
  24.     os.write(bytes,0,len);  
  25.   }  
  26.   os.close();  
  27.   in.close();  
  28.      return SUCCESS;  

这是工程中的应用,简单的例子可以参考http://dongisland.iteye.com/blog/1453613
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Qt中,可以使用QFile和QIODevice类来实现文件的上传功能。下面是一个简单的示例代码,演示如何将文件上传共享文件夹: ```cpp #include <Q> #include <Q> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> void uploadFileToSharedFolder QString& filePath, const QUrl& sharedFolderUrl) { QFile file(filePath); if (!file.open(QIODevice::)) { qDebug() << "Failed to file for reading:" << file.errorString(); return; } NetworkAccessManager manager; QNetworkRequest requestFolderUrl); QNetworkReply* reply = manager.put(request, &file); QObject::connect(reply, &QNetworkReply::finished, [&]() { if (reply->error() == QNetworkReply::NoError) { qDebug() << "File uploaded successfully!"; } else { qDebug() << "Failed to upload file:" << reply->errorString(); } reply->deleteLater(); file.close(); }); } int main() { QString filePath = "path/to/your/file.txt"; QUrl sharedFolderUrl("smb://example.com/shared_folder"); uploadFileToSharedFolder(filePath, sharedFolderUrl); return 0; } ``` 上述代码中,首先使用QFile打开要上传的文件,然后创建一个QNetworkAccessManager对象来处理网络请求。接下来,创建一个QNetworkRequest对象,并将共享文件夹的URL作为参数传递给它。然后,使用QNetworkAccessManager的put方法将文件内容发送到共享文件夹。最后,通过连接QNetworkReply的finished信号来处理上传结果。 请注意,上述示例代码中使用的是SMB协议(smb://),你需要根据实际情况修改sharedFolderUrl的值,确保它指向正确的共享文件夹。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值