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的看看吧!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值