`
god_sky
  • 浏览: 141770 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Http+Servlet 文件上传下载

    博客分类:
  • java
阅读更多

//客户端界面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>

 

分享到:
评论

相关推荐

    JSP+Servlet文件上传下载实例

    在Java Web开发中,JSP(Java...总的来说,JSP+Servlet实现文件上传下载涉及到HTML表单、Servlet请求处理、文件I/O以及第三方库的使用。通过这个实例,开发者可以掌握在Java Web环境中处理文件上传下载的基本流程。

    jsp+servlet实现文件上传下载

    ### jsp+servlet实现文件上传下载 在现代Web开发中,文件上传下载是常见的功能之一。JSP(JavaServer Pages)与Servlet技术结合可以轻松实现这一功能。本篇将详细介绍如何利用jspSmartUpload组件实现文件的上传与...

    JSP+Servlet+cos文件上传下载Jar包.rar

    "JSP+Servlet+cos文件上传下载Jar包.rar"是一个压缩包,它提供了实现这些功能所需的关键库。让我们详细了解一下这个包以及如何利用其中的资源。 1. **cos.jar**:这是China Online System(COS)的Java库,主要用于...

    Flex4.6+java+servlet上传图片例子+图片上传预览

    FileReference对象可以监听“uploadCompleteData”事件,当文件上传成功时触发。同时,通过Flash Player的StageVideo或者BitmapData类,Flex可以实现图片的实时预览功能。 在后端,Java Servlet会接收到HTTP请求,...

    jsp+servlet文件上传数据库和下载

    在Java Web开发中,"jsp+servlet文件上传数据库和下载"是常见的功能需求,涉及到的主要技术包括JSP(JavaServer Pages)、Servlet、文件处理以及数据库操作。以下将详细阐述这些知识点。 1. JSP(JavaServer Pages...

    tomcat+tomcat插件+servlet文件上传jar包

    标题中的“tomcat+tomcat插件+servlet文件上传jar包”揭示了本文将要讨论的是如何在Tomcat服务器上实现文件上传功能,并且利用相关的Tomcat插件进行辅助开发。Tomcat是一款广泛使用的开源Java Servlet容器,它实现了...

    jsp+servlet实现大型文件下载

    可能需要修改最大上传和下载文件大小限制,这通常在server.xml的Connector标签内进行。 七、安全性与性能优化 1. 防止路径遍历攻击:验证用户提供的文件路径,避免访问服务器上的敏感文件。 2. 使用异步处理:...

    使用jQuery ajaxFileUpload+servlet实现文件上传

    在这个场景下,我们将探讨如何结合`jQuery ajaxFileUpload` 和Servlet实现文件上传的功能。 首先,`jQuery ajaxFileUpload` 插件允许用户在不刷新页面的情况下上传文件,提供了一种友好的用户体验。它的主要优点...

    JSP+servlet文件上传简单案例

    在这个“JSP+servlet文件上传简单案例”中,我们将探讨如何利用这两种技术实现文件上传功能。文件上传是Web应用中常见的一种需求,例如用户可能需要上传个人头像、文档或者其他形式的数据。 首先,让我们了解一下...

    jsp+servlet实现文件上传和下载

    在这个主题中,“jsp+servlet实现文件上传和下载”是核心知识点,我们将深入探讨如何利用这两个组件以及Apache的`commons-fileupload`和`commons-io`库来完成这一任务。 1. **文件上传** 文件上传通常涉及用户通过...

    【Demo Project】ajaxSubmit+Servlet表单文件上传和下载

    【AjaxSubmit+Servlet实现表单文件上传与下载详解】 在Web开发中,文件上传和下载是常见的功能,尤其是在用户交互丰富的应用中。本项目【Demo Project】利用AjaxSubmit结合Servlet技术,提供了一种高效、异步的方式...

    jsp+servlet文件上传

    `JSP(JavaServer Pages)`和`Servlet`是Java EE平台上的两种核心技术,它们常用于构建动态Web项目,包括文件上传功能。本篇文章将深入讲解如何使用JSP和Servlet实现文件上传。 首先,我们需要了解`JSP`的基本概念...

    一个简单的JSP+Servlet图片上传例子

    这个“一个简单的JSP+Servlet图片上传例子”是一个基础教程,旨在帮助初学者理解如何通过这两种技术实现用户界面与服务器端的交互,特别是处理文件上传的功能。 首先,JSP是Java的一种视图技术,它允许开发者在HTML...

    vue+servlet的文件上传案例.rar

    本示例结合了前端的Vue.js框架和后端的Servlet技术,提供了一种实现文件上传的解决方案。Vue.js是一个轻量级的渐进式JavaScript框架,而Servlet则是Java Web开发中的核心组件,用于处理HTTP请求和响应。接下来,我们...

    纯jsp+servlet版的多文件上传与下载

    本项目以"纯jsp+servlet版的多文件上传与下载"为主题,采用MVC(Model-View-Controller)模式进行设计,这是一套广泛应用于Web开发的经典架构。下面将详细介绍这个项目中的关键知识点。 1. **MVC模式**: MVC模式...

    JSP+Servlet实现文件上传到服务器功能

    本文实例为大家分享了JSP+Servlet实现文件上传到服务器功能的具体代码,供大家参考,具体内容如下 项目目录结构大致如下: 正如我在上图红线画的三个东西:Dao、service、servlet 这三层是主要的结构,类似 MVC ...

    JSP+servlet文件上传

    在Java Web开发中,JSP(JavaServer Pages)和Servlet是两种常见的技术,它们可以协同工作来处理用户请求,包括文件上传功能。本教程将详细讲解如何使用JSP和Servlet实现文件上传,以及相关的知识点。 一、JSP与...

    jsp+servlet文件上传,非apache组件

    本教程将探讨如何使用纯JSP(JavaServer Pages)和Servlet技术来实现文件上传,而不依赖Apache的文件上传组件,如Commons FileUpload。 首先,我们需要了解JSP和Servlet的基本概念。JSP是用于创建动态网页的Java...

    jsp+servlet 图片上传

    实践中,还可能涉及到安全性优化,如使用MIME类型检查防止恶意文件上传,使用CDN存储图片以减轻服务器压力,以及使用session或cookie进行用户验证等。总的来说,理解和熟练掌握`JSP`和`Servlet`的配合使用,对于开发...

Global site tag (gtag.js) - Google Analytics