JAVA文件上传(1)

JAVA文件上传(1)

1.上传文件的方法.(客户端)


package com.test;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.UUID;

public class Shangchuan {
	public void upload(String path, File file,String key) {
		// 边界标识 随机生成,生成类似于这样的内容:07d11368-0c72-45ac-a67a-c243a085c604
		String BOUNDARY = UUID.randomUUID().toString();
		String PREFIX = "--";
		String LINE_END = "\r\n";
		String result = null;
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "utf-8");
			// 必须设定的内容
			conn.setRequestProperty("Content-Type",
					"multipart/form-data;;boundary=" + BOUNDARY);
			if (file != null) {
				DataOutputStream dos = new DataOutputStream(
						conn.getOutputStream());
				StringBuffer sb = new StringBuffer();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);
				/**
				 * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件.
				 * 这里服务端是用的servlet
				 * ,key的值就是对应servlet的映射路径。就是这里path(URL)的最后一部分:filee.
				 * filename是文件的名字,包含后缀名的 比如:abc.png
				 */
				sb.append("Content-Disposition: form-data; name=\""+key+"\"; filename=\""
						+ file.getName() + "\"" + LINE_END);
				sb.append("Content-Type: application/octet-stream; charset="
						+ "utf-8" + LINE_END);
				sb.append(LINE_END);
				dos.write(sb.toString().getBytes());
				InputStream is = new FileInputStream(file);
				byte[] bytes = new byte[1024];
				int len = 0;
				while ((len = is.read(bytes)) != -1) {
					dos.write(bytes, 0, len);
				}
				is.close();
				dos.write(LINE_END.getBytes());
				byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
						.getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 获取响应码 200=成功 当响应成功,获取响应的流
				 */
				int res = conn.getResponseCode();
				if (res == 200) {
					InputStream input = conn.getInputStream();
					StringBuffer sb1 = new StringBuffer();
					int ss;
					while ((ss = input.read()) != -1) {
						sb1.append((char) ss);
					}
					result = sb1.toString();
					System.out.println("来自服务器的信息:" + result);

				} else {
					System.out.println("连接失败!");

				}
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
2.调用上传的方法.(客户端)

package com.test;

import java.io.File;

public class Sc {
	public static void main(String[] args) {
		Shangchuan shangchuan=new Shangchuan();
		String pathname="E:\\FeiQ.exe";
		File file=new File(pathname);
		String path="http://localhost:8080/prjWebTest/filee";
		/*服务端使用的servlet,filee对应服务端的一个servlet类的映射路径*/
		String key="filee";
		shangchuan.upload(path, file,key);
	}
}
3.服务端.

负责上传文件的Servlet的代码,需要使用两个jar文件,commons-fileupload-1.2.1.jar和

commons-io-1.3.2.jar。

package com.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
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;

public class UploadServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 1、创建文件上传工厂
		DiskFileItemFactory diskfactory = new DiskFileItemFactory();
		// 2、创建上传对象
		ServletFileUpload upload = new ServletFileUpload(diskfactory);
		try {
			// 3、开始处理上传的请求
			@SuppressWarnings("unchecked")
			List<FileItem> lsitem = upload.parseRequest(req);
			// 4、获取上传的数据包括表单数据和文件数据

			for (FileItem fileItem : lsitem) {  
				// 判断是表单元素,如果是表单元素,获取表单元素的值
				if (fileItem.isFormField()) {
					System.out.println("====================================");
				} else {
					byte[] b = fileItem.get();
					String fname = fileItem.getName();
					fname = fname.substring(fname.lastIndexOf("\\") + 1);
					System.out.println("文件名字:" + fname);

					String path = this.getServletContext().getRealPath("/")
							+ "/upload/";// +fname;
					System.out.println("上传文件的路径:" + path);
					File dir = new File(path);
					if (!dir.exists()) {
						dir.mkdir();
					}
					String filepath = path + fname;
					System.out.println("文件的路径:" + filepath);
					File file = new File(filepath);
					FileOutputStream fout = new FileOutputStream(file);
					fout.write(b);
					fout.flush();
					fout.close();

				}
			}
			OutputStream out=resp.getOutputStream();
			String str="this message  to client";
			byte[]bb=str.getBytes();
			out.write(bb);
			out.flush();
			out.close();
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
}
配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>com.upload.UploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/filee</url-pattern>
    </servlet-mapping>
</web-app>

说明:这是java文件上传的一个例子(因为我主要想在Android上应用,所以在服务端没有界面文件),这里的服务端和客户端是在两个单独的java工程里面的,所以可以很方便的将这里的java客户端的代码移植到Android上面。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值