Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6643223
  • 博文数量: 915
  • 博客积分: 17977
  • 博客等级: 上将
  • 技术积分: 8846
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-26 09:59
个人简介

一个好老好老的老程序员了。

文章分类

全部博文(915)

文章存档

2022年(9)

2021年(13)

2020年(10)

2019年(40)

2018年(88)

2017年(130)

2015年(5)

2014年(12)

2013年(41)

2012年(36)

2011年(272)

2010年(1)

2009年(53)

2008年(65)

2007年(47)

2006年(81)

2005年(12)

分类: Java

2011-06-21 12:56:26

  1. import java.io.*;
  2. import javax.servlet.*;
  3. import javax.servlet.http.*;

  4. public class UploadServlet extends HttpServlet {

  5.     private static final long serialVersionUID = -6743769305857881099L;
  6.     // default maximum allowable file size is 1000k

  7.     static final int MAX_SIZE = 1024000;
  8.     // instance variables to store root and success message

  9.     String rootPath, successMessage;
  10.     FileWriter savefile;
  11.     String filename = null;
  12.     String value = null;

  13.     /**
  14.      * init method is called when servlet is initialized.
  15.      */
  16.     public void init(ServletConfig config) throws ServletException {
  17.         super.init(config);
  18.         // get path in which to save file

  19.         rootPath = config.getInitParameter("RootPath");
  20.         if (rootPath == null) {
  21.             rootPath = "/";
  22.         }
  23.         /*
  24.          * Get message to show when upload is complete. Used only if a success redirect page is not supplied.
  25.          */
  26.         successMessage = config.getInitParameter("SuccessMessage");
  27.         if (successMessage == null) {
  28.             successMessage = "File upload complete!";
  29.         }
  30.     }

  31.     /**
  32.      * doPost reads the uploaded data from the request and writes it to a file.
  33.      */
  34.     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  35.         response.setContentType("text/html");
  36.         response.setCharacterEncoding("GB2312");
  37.         PrintWriter out = response.getWriter();
  38.         // FileWriter savefile;

  39.         try {
  40.             // Verify the content type

  41.             String ct = request.getContentType();
  42.             if (!ct.startsWith("multipart/form-data"))
  43.                 throw new RuntimeException("Invalid content type");
  44.             // Get the boundary string

  45.             int p = ct.indexOf("boundary=");
  46.             if (p == -1)
  47.                 throw new RuntimeException("No boundary string found");
  48.             p += "boundary=".length();
  49.             String boundary = "--" + ct.substring(p);
  50.             String finalBoundary = boundary + "--";
  51.             // We 'll parse the multipart/form-data

  52.             // with a finite state machine

  53.             // Define names for the parser states

  54.             final int INIT = 0;
  55.             final int READING_HEADERS = 1;
  56.             final int READING_DATA = 2;
  57.             int state = INIT;
  58.             // Read and extract the fields

  59.             BufferedReader in = request.getReader();
  60.             main: for (;;) {
  61.                 String line = in.readLine();
  62.                 if (line == null)
  63.                     break;
  64.                 switch (state) {
  65.                 // State 0: Ignoring everything before

  66.                 // the first boundary

  67.                 case INIT:
  68.                     if (line.startsWith(finalBoundary))
  69.                         break main;
  70.                     if (line.startsWith(boundary)) {
  71.                         state = READING_HEADERS;
  72.                         filename = "";
  73.                         value = "";
  74.                     }
  75.                     break;
  76.                 // State 1: Parsing the headers

  77.                 case READING_HEADERS:
  78.                     if (line.length() == 0)
  79.                         state = READING_DATA;
  80.                     else {
  81.                         // Get the field name

  82.                         p = line.indexOf("filename=\"");
  83.                         if (p == -1)
  84.                             break;
  85.                         p += "filename=\"".length();

  86.                         // ... up to the closing quote.


  87.                         int q = line.indexOf("\"", p);
  88.                         if (q == -1)
  89.                             break;
  90.                         filename = line.substring(p, q);
  91.                         filename = request.getRealPath("/") + filename.substring(filename.lastIndexOf("\\") + 1);
  92.                         savefile = new FileWriter(filename);
  93.                         value = "";
  94.                     }
  95.                     break;

  96.                 // State 2: Reading the data


  97.                 case READING_DATA:
  98.                     if (line.startsWith(finalBoundary)) {
  99.                         savefile.write(value);
  100.                         savefile.close();
  101.                         break main;
  102.                     }
  103.                     if (line.startsWith(boundary)) {
  104.                         state = READING_HEADERS;
  105.                     } else {
  106.                         if (value.length() > 0)
  107.                             value += "\n";
  108.                         value += line;
  109.                     }
  110.                     break;
  111.                 }

  112.             }
  113.             // Report the incident number back to the client

  114.             String[] text = { "", "",
  115.                     "", "文件上传成功 ",
  116.                     "", "", "
    ", "

    文件上传成功!

    "
    , "
    "
    };
  117.             for (int i = 0; i < text.length; i++) {
  118.                 out.println(text[i]);
  119.             }
  120.             out.println(filename);
  121.             out.println(" ");
  122.             out.println("");
  123.         }

  124.         catch (Exception e) {
  125.             // Write the exception message

  126.             out.println("

    Error:

    "
    );
  127.             out.println("
    ");
  128.             out.println(e.getMessage());
  129.             out.println("");
  130.         } finally {
  131.             out.close();
  132.         }
  133.     }
  134. }
纯Servlet上传文件,不用Apache的FileUpload。不过使用的时候建议使用FileUpload组件,有现成的为什么不用呢?
阅读(1660) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~