唯心/

博客园 首页 联系 订阅 管理

需要用到的jar包   http://pan.baidu.com/s/1skQFk77

1.首先在一台电脑上设置共享文件夹

----上传下载的方法类

package com.strongit.tool.upload; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import jcifs.smb.SmbFile; import jcifs.smb.SmbFileInputStream; import jcifs.smb.SmbFileOutputStream; public class SMB { /** * 从本地上传文件到共享目录 * @param remoteUrl 共享文件目录 * @param localFilePath 本地文件绝对路径 */ public static void smbPut(String remoteUrl, String localFilePath) { InputStream in = null; OutputStream out = null; try { File localFile = new File(localFilePath); String fileName = localFile.getName(); SmbFile remoteFile = new SmbFile(remoteUrl+"/"+ fileName); 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]; } } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 从共享目录拷贝文件到本地 * @param remoteUrl 共享目录上的文件路径 * @param localDir 本地目录 */ public static void smbGet(String remoteUrl, String localFileStr) { InputStream in = null; OutputStream out = null; try { SmbFile remoteFile = new SmbFile(remoteUrl); remoteFile.connect(); if (remoteFile == null) { // System.out.println("共享文件不存在"); return; } String fileName = remoteFile.getName(); localFileStr = localFileStr + fileName; File localFile = new File(localFileStr); if(!localFile.exists()) { localFile.createNewFile(); } 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(); } } } }

  

2.上传的类



import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /* * smb协议 * 上传文件到另一台局域网服务器 * */ public class formservlet extends HttpServlet { //要将文件存储到远程服务器的存储地址 // smb://用户名:密码@地址/共享的目录 private static final String remoteUrl ="smb://administrator:shichengzhe@192.168.2.112/gongxiang"; public String getStr(String str) { String s=null ; if(str!=null) { try { s = new String(str.getBytes("ISO8859-1"),"gb2312"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("转码出现错误"); } } return s; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("gb2312"); response.setContentType("text/html;charset=gb2312"); //设置合法的后缀名-可以添加需要上传的文件类型 final String[] allowedatt = new String[] {"doc","docx","html","htm","txt","mp4"}; //创建该对象 DiskFileItemFactory factory = new DiskFileItemFactory(); //上传文件所用到的缓冲区大小,超过此缓冲区的部分将被写入到磁盘 factory.setSizeThreshold(4*1024); //使用fileItemFactory为参数实例化一个ServletFileUpload对象 ServletFileUpload upload = new ServletFileUpload(factory); //要求上传的form-data数据不超过1000M upload.setSizeMax(1000*1024*1024); //java.util.List实例来接收上传的表单数据和文件数据 List itemList; try { itemList = upload.parseRequest(request); //迭代list中的内容 Iterator it = itemList.iterator(); //循环list中的内容 while(it.hasNext()) { //取出一个表单域 FileItem item =(FileItem) it.next(); //如果不是普通表单,则代表是文件上传的表单 //获取上传文件的名字 String totalNameatt = getStr(item.getName()); //获取文件的后缀名 String suffixatt = totalNameatt.substring(totalNameatt.lastIndexOf(".") + 1); //判断后缀名是否是我们允许上传的类型 boolean isValide=false; for(int i=0;i<allowedatt.length;i++) { if(suffixatt.equals(allowedatt[i])){ isValide=true; break; } } //如果是不允许的类型,输出错误信息 if(!isValide) { System.out.println(totalNameatt+"该文件类型不在允许上传的范围内"); return ; } //如果是合法的,就保存该文件,文件名不变 else { //获取项目根目录 String rootPath = this.getServletConfig().getServletContext().getRealPath("/"); //要存储的文件的绝对路径 String filestr = rootPath +System.currentTimeMillis()+"."+suffixatt; File file = new File(filestr);
//获取选择上传文件的 存放到项目里面 item.write(file);
//上传到服务器 saveRemote(filestr);
//删除存放在目录里的上传文件 file.delete(); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /* * localFilePath 本地文件地址 * */ public void saveRemote(String localFilePath) { SMB.smbPut(remoteUrl, localFilePath); } }

  

3.下载文件类

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ReadServlet extends HttpServlet {

	
	private static final String remoteUrl ="smb://administrator:shichengzhe@192.168.2.112/gongxiang";
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取要获得的文件名
		String filename = request.getParameter("filename");
		//拼凑要下载文件的绝对路径
		String fileUrl = remoteUrl + "/" + filename;
		//拼凑本地路径
		String root =this.getServletConfig().getServletContext().getRealPath("/");  
		String localUrl = root+System.getProperty("file.separator")+filename;
		SMB.smbGet(fileUrl, localUrl);
		
		System.out.println("文件:"+localUrl+"下载成功");
		
	}

}

  

4.jsp页面

 

<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
  </head>
  
  <body>
    <form action="servlet/formservlet" method="post" enctype="multipart/form-data" >
        <input type="file" id="file" name="file" /><br/>
        <input type="submit" value="提交" />
    </form>

<!-- action? 要从服务器下载的文件 --> <a href="servlet/ReadServlet?filename=234234.doc">从远程服务器读取文件</a> </body> </html>

 

5.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>formservlet</servlet-name>
    <servlet-class>formservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ReadServlet</servlet-name>
    <servlet-class>ReadServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>formservlet</servlet-name>
    <url-pattern>/servlet/formservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ReadServlet</servlet-name>
    <url-pattern>/servlet/ReadServlet</url-pattern>
  </servlet-mapping>

</web-app>

 

完整的smb文件上传与下载就完成了

 

posted on 2016-07-22 11:09  唯心/  阅读(1684)  评论(0编辑  收藏  举报