利用socket实现自动上传文件

一:socket服务端,在web服务器启动时启动该服务端

public class FileSocketServer {
	public void start(){
              final int port = PropertiesUtils.getInt("socketPort");//从配置文件中获取端口
		new Thread(){
			@Override
			public void run() {
				try {
					ServerSocket server = new ServerSocket(port);
					ExecutorService pool = Executors.newFixedThreadPool(10);
					while (true) {
						try {  
							System.out.println("开始监听...");
							Socket socket = server.accept();
							System.out.println("有客户端链接");
							pool.execute(new Service(socket));
						} catch (Exception e) {
							System.out.println("服务器异常");
							e.printStackTrace();
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}.start();
	}
	
	class Service extends Thread{
		Socket socket;
		public Service(Socket socket){
			this.socket = socket;
		}
		@Override
		public void run() {
			String suffix = "";
			try {
				DataInputStream dis = new DataInputStream(socket.getInputStream());
				String line;
				while((line = readLine(dis)) != null){
					if(line.startsWith("filesuffix")){
						suffix = line.substring(11);
					}else if("file".equals(line)){
						service(suffix,dis);
						break;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		private String readLine(DataInputStream dis) throws IOException{
			byte[] buf = new byte[]{};
			int n;
			int prev =0;
			while((n = dis.read()) > 0){
				if( n == '\r'){
				}else if( n == '\n' && prev == '\r')
					break;
				else{
					buf = Arrays.copyOf(buf, buf.length+1);
					buf[buf.length-1] = (byte)n;
				}
				prev = n;
			}
			return new String(buf);
		}
		
		private void service(String suffix,DataInputStream dis){
			int length = 0;
			FileOutputStream fos = null;
			DataOutputStream dos = null;
			String filePath = "F:/"+System.currentTimeMillis()+"_"+new Random().nextInt(100)+"."+suffix;
			try {
				try {
					/* 文件存储位置 */
					fos = new FileOutputStream(new File(filePath));    
					byte[] inputByte = new byte[1024];   
					System.out.println("开始接收数据...");  
					while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) {
						fos.write(inputByte, 0, length);
						fos.flush();    
					}
					System.out.println("完成数据接收:"+filePath);
					//
					System.out.println("响应客户端……");
					dos = new DataOutputStream(socket.getOutputStream());
					dos.write((filePath+"\r\n").getBytes());
					dos.flush();
					System.out.println("数据发送完毕");
				} finally {
					if (fos != null)	fos.close();
					if(dis != null)		dis.close();
					if(dos != null)		dos.close();
					if(socket != null)	socket.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
}

二:socket客户端

public class FileSocketClient {
	public String start(String filepath){
		Socket socket = new Socket();  
		try {
                     //从配置文件获取服务器IP和端口
			String serverIP = PropertiesUtils.getString("socketServerIP");
			int port = PropertiesUtils.getInt("socketPort");
			socket.connect(new InetSocketAddress(serverIP, port));
			String serverPath = new SocketClient(socket,filepath).call();
			return serverPath;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	class SocketClient implements Callable<String>{
		Socket socket;
		String filepath;
		public SocketClient(Socket socket,String filepath){
			this.socket = socket;
			this.filepath = filepath;
		}
		@Override
		public String call() {
			try {
				OutputStream os = socket.getOutputStream();
				os.write("filesuffix:jpg\r\n".getBytes());
				os.write("file\r\n".getBytes());
				return service();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return "";
		}
		private String service(){
			DecimalFormat df = new DecimalFormat("00.00");
			int length = 0;
			double sumL = 0 ;
			DataOutputStream dos = null;
			Scanner console = null;
			FileInputStream fis = null;
			boolean bool = false;
			try {
				File file = new File(filepath); //要传输的文件路径
				long l = file.length(); 
				dos = new DataOutputStream(socket.getOutputStream());
				fis = new FileInputStream(file);      
				byte[] sendBytes = new byte[1024];  
				while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
					sumL += length;  
					System.out.println("已传输:"+df.format(((sumL/l)*100))+"%");
					dos.write(sendBytes, 0, length);
					dos.flush();
				} 
				if(sumL==l){
					bool = true;
				}
				socket.shutdownOutput();
				//输入流  
				console = new Scanner(socket.getInputStream());  
	                        //接收服务器的相应  
	                        String line = console.nextLine();
	                        return line;
			}catch (Exception e) {
				System.out.println("客户端文件传输异常");
				bool = false;
				e.printStackTrace();  
			} finally{  
				try {
					if (dos != null)	dos.close();
					if (fis != null)	fis.close();   
					if(console != null)	console.close();
					if (socket != null)	socket.close();    
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			System.out.println(bool?"成功":"失败");
			return "";
		}
	}

}

三:自动上传文件jsp

<%@page contentType="text/html;charset=utf-8" pageEncoding="UTF-8"%>
<%@page import="com.util.socket.FileSocketClient" %>
<%
String filepath = request.getParameter("filepath");
String code = request.getParameter("uniqueCode");
String uniqueCode = (String)session.getAttribute("uniquetag");
//条件判断 
if(filepath != null && uniqueCode != null && uniqueCode.equals(code)){
	String serverpath = new FileSocketClient().start(filepath);
	response.getWriter().print(serverpath);
}
%>

下面是个测试小实例

前台jsp表单

<head>
		<title></title>
		<script type="text/javascript" src="${ctx}/js/jquery-1.7.2.js"></script>
		<script type="text/javascript">
			function upload(){
				var code = $("#unq").val();
				$.ajax({
					url:"${ctx}/autoupload.jsp",
					data:"filepath=F:/my.jpg&uniqueCode="+code,
					type:"post",
					dataType:"text",
					async:false,
					success:function(data){
						$("#objform").append("<input type='hidden' name='filepath' value='"+data+"'/>");
					}
				});
				return true;
			}
		</script>
	</head>
	<body>
		<form action="${ctx }/autoupload.action" method="post" οnsubmit="return upload()" id="objform">
			<!-- 随机生成唯一字符串并保存在session中  -->
                     <jt:unique id="unq"/>
			<input name="name"/><br/>
			<input name="age"/><br/>
			<input type="submit" value="提交"/>
		</form>
		
	</body>

后台Action

public String autoUpload() throws Exception{
		String path = request.getParameter("filepath");
		System.out.println(path);
		System.out.println(request.getParameter("name"));
		System.out.println(request.getParameter("age"));
		return SUCCESS;
}
OK啦,在action中可以获取文件上传到服务器后的file地址


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值