Http+Servlet 文件上传下载
//客户端界面package com.sky.client.face;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import com.sky.client.remotecall.Http;
import com.sky.http.bean.CallParam;
import com.sky.http.bean.CallResult;
//客服端
public class MyFrame extends JFrame {
?/**
? * @param args
? */
?public static String host = "localhost";// ip地址
?public static int port = 8080;// 端口
?public static String page = null;// 请求的Servlet页面
?public JButton send;
?public JButton down;
?public JPanel panel;
?public MyFrame() {
??panel = new JPanel();
??panel.setLayout(null);
??this.add(panel);
??send = new JButton("上传");
??send.setBounds(20, 30, 60, 40);
??ButtonEvent butEvent = new ButtonEvent();
??send.addActionListener(butEvent);
??panel.add(send);
??down = new JButton("下载");
??down.setBounds(100, 30, 60, 40);
??ButtonDown butDown = new ButtonDown();
??down.addActionListener(butDown);
??panel.add(down);
?}
?/*
? * 文件上传
? */
?public class ButtonEvent implements ActionListener {
??public void actionPerformed(ActionEvent e4) {
???CallParam param = new CallParam();
???param.setPage("/httpServce/fileUpload");// 111.png
???JFileChooser fileChooser = new JFileChooser();
???int i = fileChooser.showSaveDialog(MyFrame.this);// 1表示取消上传,0确定上传
???if (i == JFileChooser.APPROVE_OPTION) {
????File file = fileChooser.getSelectedFile();
????// 本地保存路径,文件名会自动从服务器端继承而来。
????FileInputStream input = null;
????try {
?????int bytesize=0;
?????byte[] tempbytes = new byte[(int) file.length()];
?????System.out.println("byte数组的大小:"+tempbytes.length);
?????int byteread = 0;//byteread为一次读入的字节数
?????// 读入多个字节到字节数组中,byteread为一次读入的字节数
?????input = new FileInputStream(file);
?????System.out.println("文件的长度:"+file.length());
?????int line=1;
?????while ((byteread = input.read(tempbytes)) != -1) {
??????System.out.println(line+"次读入的字节数:"+byteread);
??????line++;??????
??????bytesize+=byteread;
?????}
?????System.out.println("文件总字节数:"+bytesize);
?????System.out.println("文件名:"+file.getName());
?????param.setByt(tempbytes);
?????param.setFileName(file.getName());
?????CallResult result = remoteCall(param);
?????result.isSuccess();
?????System.out.println(result.isSuccess()+ "==============返回结果============");
?????JOptionPane.showMessageDialog(MyFrame.this,"上传文件成功");
????} catch (FileNotFoundException e) {
?????e.printStackTrace();
????} catch (IOException e) {
?????e.printStackTrace();
????} catch (Exception e) {
?????e.printStackTrace();
????}
????
???}
??}
?}
?
?/*
? * 文件下载
? */
?public class ButtonDown implements ActionListener {
??public void actionPerformed(ActionEvent e4) {
???System.out.println("------------点击下载------------");
???CallParam param = new CallParam();
???param.setPage("/httpServce/fileDown");// 要请求的Servlet
???param.setFileName("E://2011-09-02//遗留问题.txt");//要下载的文件目录
???CallResult result = null;
???try {
????result = remoteCall(param);
???} catch (Exception e) {
????e.printStackTrace();
???}
???byte[] tempbytes=result.getByt();
???JFileChooser fileChooser = new JFileChooser();
???fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
???int i = fileChooser.showSaveDialog(MyFrame.this);// 1表示取消上传,0确定上传
???if (i == JFileChooser.APPROVE_OPTION) {
????File file = fileChooser.getSelectedFile();
????// 本地保存路径,文件名会自动从服务器端继承而来。
????String savePath = file.getAbsolutePath();
????System.out.println(savePath+"文件路====================");
????savePath +=File.separator+"遗留问题.txt";
????FileOutputStream output = null;
????try {
?????output = new FileOutputStream(new File(savePath));
?????output.write(tempbytes);
?????output.flush();
?????output.close();
?????JOptionPane.showMessageDialog(null, "文件下载成功");
????} catch (FileNotFoundException e) {
?????e.printStackTrace();
????} catch (IOException e) {
?????e.printStackTrace();
????}
???}
???System.out.println(result.isSuccess()+ "==============返回结果============");
??}
?}
?/**
? *
? * @param param
? * @return
? * @throws Exception
? * 请求的方法
? */
?public CallResult remoteCall(CallParam param) throws Exception {
??Http h = new Http(host, port, param.getPage());
//??h.setCookie(ClientEnv.getInstance().getCookie());
??ByteArrayOutputStream bout = new ByteArrayOutputStream();// 创建一个新的 byte 数组输出流。
??ObjectOutputStream objOut = new ObjectOutputStream(bout);//
??objOut.writeObject(param);
??byte[] bytes = bout.toByteArray();
??param.getByt();
??h.sendRequest(bytes);
??ByteArrayInputStream bin = new ByteArrayInputStream(h.responseBytes);
??ObjectInputStream objIn = new ObjectInputStream(bin);
??Object objResult = objIn.readObject();
??CallResult result = (CallResult) objResult;??
??return result;
?}
?public static void main(String[] args) {
??MyFrame mybtn = new MyFrame();
??mybtn.setSize(200, 120);
??mybtn.setVisible(true);
??mybtn.setLocation(300, 220);
??mybtn.setTitle("socket文件的上传下载");
??mybtn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
?}
}
?
?
?
//Http类
?
?
/**
?*
?*/
package com.sky.client.remotecall;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.Vector;
/**
?* @author Ricky
?*
?*/
public class Http {
?public Vector<String> vHeader = new Vector<String>();
?public String method = null;
?public String host = null;
?public int port = 80;
?public String page = null;
?public String httpStr = "HTTP/1.1";
?
?public PrintWriter pw = null;
?public InputStream in = null;
?public OutputStream out = null;
?
?public HashMap<String, String> responseMap = new HashMap<String, String>();
?public String responseText = null;
?public int responseCode = 0;
?public byte [] responseBytes = null;
?public boolean convertToText = true;
?
?public String hexString = "0123456789ABCDEF";
//?public Cookie cookie = null;
?public int socketTimeout = 120000;
?
?public Http(String host,String page) {
??this(host,80,page,"POST");
?}
?
?public Http(String host,int port,String page) {
??this(host,port,page,"POST");
?}
?
?public Http(String host,int port,String page,String method) {
??this.host = host;
??this.page = page;
??this.port = port;
??this.method = method;
??initHeader();
?}
?/**
? * 设置头信息
? */
?public void initHeader() {
??try {
???addHeader("Accept: */*");//请求报头域用于指定客户端接受哪些类型的信息,此表示所有类型的信息。
???addHeader("Accept-Language: zh-cn");//接受语言类型
???if(method.equalsIgnoreCase("POST")) {
????addHeader("Content-Type: application/x-www-form-urlencoded;");//实体报头域用语指明发送给接收者的实体正文的媒体类型,此表示为复杂类型。
???}
???addHeader("UA-CPU: x86");//
???addHeader("User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; )");
???addHeader("Host: "+host);
??} catch (Exception e) {
???e.printStackTrace();
??}
?}
?
?public void addHeader(String keyValue) throws Exception {
??vHeader.add(keyValue);
?}
?
?public void addHeader(String key,String value) throws Exception {
??vHeader.add(key+": "+value);
?}
?
?public void println(String line) throws Exception {
??//System.out.println("[S]"+line);
??pw.println(line);
??pw.flush();
?}
?
?public void println() throws Exception {
??//System.out.println("[S]");
??pw.println();
??pw.flush();
?}
?
?public void write(byte [] bytes) throws Exception {
??
?}
?
?public void print(String line) throws Exception {
??//System.out.println("[S]"+line);
??pw.print(line);
??pw.flush();
?}
?
?public String readLine() throws Exception {
??byte [] buff = new byte[1024];
??int len = -1;
??for (int i = 0; i < buff.length; i++) {
???int n = in.read();
???if(i==buff.length-1) {
????len = i;
????break;
???}
???if(n=='\r') {
????len = i;
????in.read();
????break;
???}
???if(n=='\n') {
????len = i;
????break;
???}
???buff[i] = (byte)n;
??}
??if(len==-1) return null;
??String line = new String(buff,0,len);
??//System.out.println("[R]"+line);
??return line;
?}
?
?public static void main(String [] args) {
??try {
???Http http = new Http("", "");
???System.out.println(http.hexToInt("2097"));
??} catch (Exception e) {
???
??}
?}
?
?public int hexToInt(String str) throws Exception {
??if(str==null||str.trim().length()==0) return 0;
??char [] hexNumber = str.trim().toUpperCase().toCharArray();
??char [] hexChar = hexString.toCharArray();
??int n = 0;
??for (int i = 0; i < hexNumber.length; i++) {
???boolean valid = false;
???for (int j = 0; j < hexChar.length; j++) {
????if(hexNumber[i]==hexChar[j]) {
?????n+=(j*Math.pow(16, hexNumber.length-i-1));
?????valid = true;
????}
???}
???if(!valid) return 0;
??}
??return n;
?}
?/**
? *
? * @param line
? * @return
? * @throws Exception
? * 解析头文件
? */
?
?public boolean parseHeader(String line) throws Exception {
??if(line==null || line.trim().length()==0) return false;
??int index = line.indexOf(":");
??if(index==-1) return true;
??String key = line.substring(0,index).trim();
??String value = line.substring(index+1,line.length()).trim();
??responseMap.put(key, value);
??return true;
?}
?
?public int readAll(InputStream in,byte [] buff) throws Exception {
??int index = 0;
??int length = buff.length;
??while(true) {
???int len = in.read(buff,index,length-index);
???if(len==-1) return index;
???index+=len;
???if(index>=length-1) break;
??}
??return length;
?}
??/**
?? *
?? * @param content
?? * @throws Exception
?? * 发送String类型的数据
?? */
?public void sendRequest(String content) throws Exception {
??
??Socket s = new Socket();
??try {
???s.setSoTimeout(120000);
???s.connect(new InetSocketAddress(host, 80),120000);
???in = s.getInputStream();
???out = s.getOutputStream();
???pw = new PrintWriter(out);
???responseBytes = null;
???if(content!=null) {
????addHeader("Content-Length", ""+content.getBytes().length);
???}
//???if(cookie!=null) {
//????String strCookie = cookie.getCookie();
//????if(strCookie!=null && strCookie.trim().length()>0) {
//?????addHeader("Cookie",strCookie);
//????}
//???}
???println(method+" "+page+" "+httpStr);
???for (int i = 0; i < vHeader.size(); i++) {
????String str = vHeader.get(i);
????println(str);
???}
???println();
???if(content!=null) print(content);
???
???
???String line = null;
???
???line = readLine();
???int index1 = line.indexOf(" ");
???if(index1==-1) throw new Exception("未能解析状态码");
???int index2 = line.indexOf(" ", index1+1);
???String code = line.substring(index1+1,index2);
???//System.out.println("状态码:["+code+"]");
???
???responseCode = Integer.parseInt(code);
???
???while((line=readLine())!=null) {
????if(!parseHeader(line)) break;
???}
???
???String strCookie = responseMap.get("Set-Cookie");
//???if(strCookie!=null && cookie!=null) {
//????cookie.setCookie(strCookie);
//???}
???
???String strContentLength = responseMap.get("Content-Length");
???String strTransferEncoding = responseMap.get("Transfer-Encoding");
???if(strContentLength!=null) {
????int contentLength = Integer.parseInt(strContentLength);
????byte [] response = new byte[contentLength];
????
????readAll(in, response);
????responseBytes = response;
????
???} else if(strTransferEncoding!=null && strTransferEncoding.equalsIgnoreCase("chunked") ) {
????ByteArrayOutputStream bout = new ByteArrayOutputStream();
????
????while(true) {
?????String strLen = readLine();
?????int len = hexToInt(strLen);
?????if(len==0) break;
?????byte [] buff = new byte[len];
?????readAll(in, buff);?????
?????bout.write(buff, 0, len);
?????readLine();
????}
????
????responseBytes = bout.toByteArray();
????
????
???}
???
???if(responseBytes!=null && convertToText) {
????String strResponse = new String(responseBytes,"GBK");
????
????//System.out.println("================response begin===============");
????//System.out.println(strResponse);
????//System.out.println("================response end=================");
????responseText = strResponse;
???}
??} catch (Exception ex) {
???ex.printStackTrace();
???throw ex;
??} finally {
???try {in.close();} catch (Exception e) {}
???try {out.close();} catch (Exception e) {}
???try {s.close();} catch (Exception e) {}
??}
??
?}
?
?/**
? *
? * @param content
? * @throws Exception
? * 发送byte类型的数据
? */
?public void sendRequest(byte [] content) throws Exception {
??
??Socket s = new Socket();
??try {
???s.setSoTimeout(socketTimeout);
???s.connect(new InetSocketAddress(host, port),socketTimeout);
???in = s.getInputStream();
???out = s.getOutputStream();
???pw = new PrintWriter(out);
???responseBytes = null;
???if(content!=null) {
????addHeader("Content-Length", ""+content.length);//添加传输内容
???}
//???if(cookie!=null) {
////????String cookieStr=null;
//????String strCookie = cookie.getCookie();
//????if(strCookie!=null && strCookie.trim().length()>0) {
//?????addHeader("Cookie",strCookie);
//????}
//???}
???println(method+" "+page+" "+httpStr);
???for (int i = 0; i < vHeader.size(); i++) {
????String str = vHeader.get(i);
????println(str);
???}
???println();
???if(content!=null){
????out.write(content);
???}
??????
???String line = null;
???
???line = readLine();
???int index1 = line.indexOf(" ");
???if(index1==-1) throw new Exception("未能解析状态码");
???int index2 = line.indexOf(" ", index1+1);
???String code = line.substring(index1+1,index2);
???if(!code.equals("200")) throw new Exception("错误的响应码:["+code+"]");
???
???responseCode = Integer.parseInt(code);
???
???while((line=readLine())!=null) {
????if(!parseHeader(line)) break;
???}
???
//???String strCookie = responseMap.get("Set-Cookie");
//???if(strCookie!=null && cookie!=null) {
//????cookie.setCookie(strCookie);
//???}
???
???String strContentLength = responseMap.get("Content-Length");
???String strTransferEncoding = responseMap.get("Transfer-Encoding");
???if(strContentLength!=null) {
????int contentLength = Integer.parseInt(strContentLength);
????byte [] response = new byte[contentLength];
????
????readAll(in, response);
????responseBytes = response;
????
???} else if(strTransferEncoding!=null && strTransferEncoding.equalsIgnoreCase("chunked") ) {
????ByteArrayOutputStream bout = new ByteArrayOutputStream();
????
????while(true) {
?????String strLen = readLine();
?????int len = hexToInt(strLen);
?????if(len==0) break;
?????byte [] buff = new byte[len];
?????readAll(in, buff);?????
?????bout.write(buff, 0, len);
?????readLine();
????}
????
????responseBytes = bout.toByteArray();
????
????
???}
???
???if(responseBytes!=null && convertToText) {
????String strResponse = new String(responseBytes,"GBK");
????
????//System.out.println("================response begin===============");
????//System.out.println(strResponse);
????//System.out.println("================response end=================");
????responseText = strResponse;
???}
??} catch (Exception ex) {
???throw ex;
??} finally {
???try {in.close();} catch (Exception e) {}
???try {out.close();} catch (Exception e) {}
???try {s.close();} catch (Exception e) {}
??}
??
?}
?public String getResponseText() {
??return responseText;
?}
?public void setResponseText(String responseText) {
??this.responseText = responseText;
?}
?public int getResponseCode() {
??return responseCode;
?}
?public void setResponseCode(int reponseCode) {
??this.responseCode = reponseCode;
?}
?public byte[] getResponseBytes() {
??return responseBytes;
?}
?public void setResponseBytes(byte[] reponseBytes) {
??this.responseBytes = reponseBytes;
?}
?public boolean isConvertToText() {
??return convertToText;
?}
?public void setConvertToText(boolean convertToText) {
??this.convertToText = convertToText;
?}
//?public Cookie getCookie() {
//??return cookie;
//?}
//
//?public void setCookie(Cookie cookie) {
//??this.cookie = cookie;
//?}
}
?
//发送数据类
/**
?*
?*/
package com.sky.http.bean;
import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.util.ArrayList;
/**
?* @author Ricky
?* 请求数据类
?*/
public class CallParam implements Serializable {
?
?public String page = null;?//请求的Servlet
?
?public byte[] byt=null;??//传输的byt数据
?public String fileName;??//文件名
?public CallParam() {
?}
?
?public byte[] getByt() {
??return byt;
?}
?public void setByt(byte[] byt) {
??this.byt = byt;
?}
?public String getFileName() {
??return fileName;
?}
?public void setFileName(String fileName) {
??this.fileName = fileName;
?}
?public String getPage() {
??return page;
?}
?public void setPage(String page) {
??this.page = page;
?}
}
//返回数据类
?
/**
?*
?*/
package com.sky.http.bean;
import java.io.Serializable;
/**
?* @author Ricky
?*返回结果类
?*/
public class CallResult implements Serializable {
//?public String exceptionName = null;
//?public String exceptionStack = null;
//?public Object result = null;
?public boolean success = true;?
?public byte[] byt=null;
?
?
?/**
? *
? */
?public CallResult() {
?}
?
?public byte[] getByt() {
??return byt;
?}
?public void setByt(byte[] byt) {
??this.byt = byt;
?}
//?public Object getResult() {
//??return result;
//?}
//
//?public void setResult(Object result) {
//??this.result = result;
//?}
//
//?public String getExceptionName() {
//??return exceptionName;
//?}
//
//?public void setExceptionName(String exceptionName) {
//??this.exceptionName = exceptionName;
//?}
//
//?public String getExceptionStack() {
//??return exceptionStack;
//?}
//
//?public void setExceptionStack(String exceptionStack) {
//??this.exceptionStack = exceptionStack;
//?}
?public boolean isSuccess() {
??return success;
?}
?public void setSuccess(boolean success) {
??this.success = success;
?}
}
//文件上传类
package com.sky.http.servlets;
?
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sky.http.bean.CallParam;
import com.sky.http.bean.CallResult;
//import com.sky.http.remoteservice.RemoteContext;
public class FileUploadServlet extends HttpServlet {
?/**
? *
? */
?public FileUploadServlet() {
?}
?
?public int readAll(InputStream in,byte [] buff) throws Exception {
??int index = 0;
??int length = buff.length;
??while(true) {
???int len = in.read(buff,index,length-index);
???System.out.println("长度:"+length);
???if(len==-1) return index;
???index+=len;
???System.out.println("index:"+index);
???if(index>=length-1) break;
??}
??return length;
?}
?
?
?/**
? * 文件上传
? *
? */
?protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
??
//??request.setCharacterEncoding("utf-8");
//??response.setContentType("text/html;charset=utf-8");//不写不能输出中文;
//
??System.out.println("==============提交到Servlet了================");
//??String user=request.getParameter("user");
//??String age=request.getParameter("age");
//??PrintWriter write=response.getWriter();
//??write.println("用户:"+user);
//??write.println("年龄:"+age);
??
??CallResult callResult = new CallResult();
//??RemoteContext.getInstance().putContext(request, response);
??try {???
???String contentLength = request.getHeader("content-length");//得到内容的长度
???int nContentLen = Integer.parseInt(contentLength);
???byte [] buff = new byte[nContentLen];
???InputStream reqIn = request.getInputStream();
???System.out.println("我是中国人:"+reqIn);
???readAll(reqIn, buff);
???System.out.println("返回值哦!!!");
???
???ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(buff));
???System.out.println("返回值哦!!!");
???CallParam param = (CallParam)objIn.readObject();?
???SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");??
???String path=sdf.format(new Date());
???String filePath = "E:" + File.separator+path ;
???System.out.println("============================上传文件夹:"+filePath);
???File file = new File(filePath);
???if (file.exists()) {
????file.delete();
???} else {
????file.mkdirs();
???}
???byte[] tempbytes=param.getByt();
???System.out.println(param.getPage()+"文件名:"+param.getFileName());
???FileOutputStream outSTr = new FileOutputStream(new File(filePath+ File.separator +param.getFileName()));
???outSTr.write(tempbytes);
//???outSTr.flush();
//???outSTr.close();
???callResult.setSuccess(true);
???
??} catch (Exception e) {
???Throwable th = null;
???
???if(e!=null && e instanceof InvocationTargetException) {
????th = ((InvocationTargetException) e).getTargetException();
???} else {
????th = e;
???}
???
???th.printStackTrace();
??
???
??}
//??finally {
//???RemoteContext.getInstance().removeContext();
//??}
??
??try {
???ObjectOutputStream objOut = new ObjectOutputStream(response.getOutputStream());
???objOut.writeObject(callResult);
??} catch (Exception e) {
???e.printStackTrace();
???throw new ServletException(e.getMessage());
??}
??
?}
?protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
??this.doPost(request, response);
?}
?
}
?
?
?
//文件下载类
package com.sky.http.servlets;
?
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sky.http.bean.CallParam;
import com.sky.http.bean.CallResult;
//import com.sky.http.remoteservice.RemoteContext;
public class FileDownloadServlet extends HttpServlet {
?public int readAll(InputStream in, byte[] buff) throws Exception {
??int index = 0;
??int length = buff.length;
??while (true) {
???int len = in.read(buff, index, length - index);
???if (len == -1)
????return index;
???index += len;
???if (index >= length - 1)
????break;
??}
??return length;
?}
?protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
??System.out.println("--------------------提交到Servlet了-------------------");
??CallResult callResult = new CallResult();
//??RemoteContext.getInstance().putContext(request, response);
??try {
???String contentLength = request.getHeader("content-length");
???int nContentLen = Integer.parseInt(contentLength);
???byte[] buff = new byte[nContentLen];
???InputStream reqIn = request.getInputStream();
???readAll(reqIn, buff);
???ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(buff));
???CallParam p = (CallParam) objIn.readObject();
???
???String filePath =p.getFileName();
???System.out.println("下载文件路径================="+filePath);
???File file=new File(filePath);
???FileInputStream input = new FileInputStream(file);
???byte[] tempbytes = new byte[(int) file.length()];
???int byteread = 0;
???int bytesize=0;
???// 读入多个字节到字节数组中,byteread为一次读入的字节数
???while ((byteread = input.read(tempbytes)) != -1) {
//????bytesize+=byteread;
???}
//???int reads = 0;
//???byte[] bytes = new byte[1024];
//???while ((reads = input.read(bytes)) != -1) {
//???}
???callResult.setByt(tempbytes);
???input.close();
??} catch (Exception e) {
???Throwable th = null;
???if (e != null && e instanceof InvocationTargetException) {
????th = ((InvocationTargetException) e).getTargetException();
???} else {
????th = e;
???}
???th.printStackTrace();
??}
//??finally {
//???RemoteContext.getInstance().removeContext();
//??}
??try {
???ObjectOutputStream objOut = new ObjectOutputStream(response.getOutputStream());
???objOut.writeObject(callResult);
??} catch (Exception e) {
???e.printStackTrace();
???throw new ServletException(e.getMessage());
??}
?}
?protected void doGet(HttpServletRequest request,
???HttpServletResponse response) throws ServletException, IOException {
??this.doPost(request, response);
?}
}
?
?
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
?<display-name>httpServce</display-name>
?<!-- 文件上传 -->
?<servlet>
??<servlet-name>fileUpload</servlet-name>
??<servlet-class>com.sky.http.servlets.FileUploadServlet</servlet-class>
?</servlet>
?<servlet-mapping>
??<servlet-name>fileUpload</servlet-name>
??<url-pattern>/fileUpload</url-pattern>
?</servlet-mapping>
<!-- 文件上传 -->
<!-- 文件下载 -->
?<servlet>
??<servlet-name>fileDown</servlet-name>
??<servlet-class>com.sky.http.servlets.FileDownloadServlet</servlet-class>
?</servlet>
?<servlet-mapping>
??<servlet-name>fileDown</servlet-name>
??<url-pattern>/fileDown</url-pattern>
?</servlet-mapping>
<!-- 文件下载 -->
?<welcome-file-list>
??<welcome-file>index.html</welcome-file>
??<welcome-file>index.htm</welcome-file>
??<welcome-file>index.jsp</welcome-file>
??<welcome-file>default.html</welcome-file>
??<welcome-file>default.htm</welcome-file>
??<welcome-file>default.jsp</welcome-file>
?</welcome-file-list>
</web-app>
?