Servlet上传文件源码,不用控件,帮助你理解

1

得到数据

 

2

根据boundary分块

 

3

对块进行不同的处理

 

 

 

代码:

 

package org.quasar.loader.uploader;

import static java.lang.System.out;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
 * @author Quasar
 * @version 0.1
 *  This servlet complete the function that allows a client to upload a file;
 *  The main idea is to analyse the inputstream and give the right response.
 */
public class UploadServlet extends HttpServlet {
 
  public void doGet(HttpServletRequest req, HttpServletResponse resp) {
   doPost(req, resp);
  }
  
  public void doPost(HttpServletRequest req, HttpServletResponse resp) {
   HttpSession session = req.getSession(true);
   //define two state:Header represents no-operation;key represents a input type header;
   final int HEADER = 0;
   final int KEY = 1;
   //get all the data of form,and write them into br.
   String sdata = getFormData(req);
   out.println(sdata);
   BufferedReader br = new BufferedReader(new StringReader(sdata));
   
   //get Boundary and endBoundary
   String contentType = req.getContentType();
   String boundary = getBoundary(contentType);
   String endBoundary = boundary + "--";
   out.println("boundary:" + boundary);
   //start analyze data
   int state = HEADER;
   String sline = new String();
   try {
    while((sline=br.readLine())  != null) {
     switch(state) {
     case HEADER:
      if(sline.startsWith(boundary)) {
       state = KEY;
      }
      break;
     case KEY:
         int keyStart = sline.indexOf("name=") + new String("name=").length() + 1;
         out.println(keyStart);
         int keyEnd =  sline.indexOf(";", keyStart) - 1;
         out.println(keyEnd);
         String name = null;
         if(keyEnd < 0) {
          name = sline.substring(keyStart, sline.length()  - 1);
         } else {
          name = sline.substring(keyStart, keyEnd);
         }
        out.println("Key-Name:" + name);
        solveData(name.trim(), session, br, endBoundary);
        state = HEADER;
      break;
        default:
      out.println("KEY HEADER :update it!");
            break;
     }
    }
   } catch (IOException e) {
    out.println("Get data error at analyze stage!");
    e.printStackTrace();
   }
  }
  
  private String getFormData(HttpServletRequest req) {
   String sdata = null;
   try {
    DataInputStream dis = new DataInputStream(req.getInputStream());
       int length = req.getContentLength();
       byte[] buffer = new byte[length];
       dis.readFully(buffer);
       sdata = new String(buffer);
   } catch (IOException e) {
    out.println("Can't get inputstream!");
    e.printStackTrace();
   }
   return sdata;
  }
  
  private String getBoundary(String contenttype) {
   String boundary = null;
   int pos = contenttype.indexOf("boundary") + "boundary=".length();
   int posend = contenttype.indexOf(";", pos) - 1;
   boundary = "--" + contenttype.substring(pos) ;
   return boundary;
  }
  
  private void solveData(String name, HttpSession session, BufferedReader br, String endBoundary ) {
   if(name.equals("fileid") ) {
     try {
      while(br.readLine().equals("/r/n")) {
       break;
      }
      String fileid = br.readLine().trim();
      out.println("fieldid:" + fileid);
      session.setAttribute("fileid", fileid);
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
   } else if(name .equals("filetype") ) {
    try {
     while(br.readLine().equals("/r/n")) {
      break;
     }
     String filetype = br.readLine().trim();
     out.println("filetype:" + filetype);
     session.setAttribute("filetype", filetype);
     
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   } else if(name .equals("filedata") ) {
       String sin = null;
       DataOutputStream dos = null;
       File pic = new File("C://upload.jpg");
       try {
     dos = new DataOutputStream(new FileOutputStream(pic));
    } catch (FileNotFoundException e1) {
     out.println("Into File Error!");
     e1.printStackTrace();
    }
     try {
      while(br.readLine().equals("/r/n")) {
       break;
      }
      /*
         我猜是编码问题,保存为图片后,打不开!高手帮帮我!
         保存后,与上传的原图片文件大小不同,一个是1.57k另一个1.17K,怎么解决?
      */
      while(!(sin = br.readLine()).startsWith(endBoundary)) {
       //String bsin = new String(sin.getBytes(), "gbk");
       byte[] buffer = sin.getBytes("utf-8");
       dos.write(buffer);
       dos.flush();
      }
      dos.flush();
      dos.close();
      out.println("OK!");
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    try {
     pic.createNewFile();
    } catch (IOException e) {
     out.println("Can't save!");
     e.printStackTrace();
    }
   } else {
    out.println("Update it!");
   }
 }
}

参考:

Servlet高级编程,想学好Web的看看吧!

 

你可能感兴趣的:(servlet,String,session,header,null,buffer)