- import java.io.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- public class UploadServlet extends HttpServlet {
- private static final long serialVersionUID = -6743769305857881099L;
- // default maximum allowable file size is 1000k
- static final int MAX_SIZE = 1024000;
- // instance variables to store root and success message
- String rootPath, successMessage;
- FileWriter savefile;
- String filename = null;
- String value = null;
- /**
- * init method is called when servlet is initialized.
- */
- public void init(ServletConfig config) throws ServletException {
- super.init(config);
- // get path in which to save file
- rootPath = config.getInitParameter("RootPath");
- if (rootPath == null) {
- rootPath = "/";
- }
- /*
- * Get message to show when upload is complete. Used only if a success redirect page is not supplied.
- */
- successMessage = config.getInitParameter("SuccessMessage");
- if (successMessage == null) {
- successMessage = "File upload complete!";
- }
- }
- /**
- * doPost reads the uploaded data from the request and writes it to a file.
- */
- public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- response.setContentType("text/html");
- response.setCharacterEncoding("GB2312");
- PrintWriter out = response.getWriter();
- // FileWriter savefile;
- try {
- // Verify the content type
- String ct = request.getContentType();
- if (!ct.startsWith("multipart/form-data"))
- throw new RuntimeException("Invalid content type");
- // Get the boundary string
- int p = ct.indexOf("boundary=");
- if (p == -1)
- throw new RuntimeException("No boundary string found");
- p += "boundary=".length();
- String boundary = "--" + ct.substring(p);
- String finalBoundary = boundary + "--";
- // We 'll parse the multipart/form-data
- // with a finite state machine
- // Define names for the parser states
- final int INIT = 0;
- final int READING_HEADERS = 1;
- final int READING_DATA = 2;
- int state = INIT;
- // Read and extract the fields
- BufferedReader in = request.getReader();
- main: for (;;) {
- String line = in.readLine();
- if (line == null)
- break;
- switch (state) {
- // State 0: Ignoring everything before
- // the first boundary
- case INIT:
- if (line.startsWith(finalBoundary))
- break main;
- if (line.startsWith(boundary)) {
- state = READING_HEADERS;
- filename = "";
- value = "";
- }
- break;
- // State 1: Parsing the headers
- case READING_HEADERS:
- if (line.length() == 0)
- state = READING_DATA;
- else {
- // Get the field name
- p = line.indexOf("filename=\"");
- if (p == -1)
- break;
- p += "filename=\"".length();
- // ... up to the closing quote.
- int q = line.indexOf("\"", p);
- if (q == -1)
- break;
- filename = line.substring(p, q);
- filename = request.getRealPath("/") + filename.substring(filename.lastIndexOf("\\") + 1);
- savefile = new FileWriter(filename);
- value = "";
- }
- break;
- // State 2: Reading the data
- case READING_DATA:
- if (line.startsWith(finalBoundary)) {
- savefile.write(value);
- savefile.close();
- break main;
- }
- if (line.startsWith(boundary)) {
- state = READING_HEADERS;
- } else {
- if (value.length() > 0)
- value += "\n";
- value += line;
- }
- break;
- }
- }
- // Report the incident number back to the client
- String[] text = { "", "",
- "", "文件上传成功 ",
- "", "", "", "
文件上传成功!
", "" };
- for (int i = 0; i < text.length; i++) {
- out.println(text[i]);
- }
- out.println(filename);
- out.println("
");
- out.println("");
- }
- catch (Exception e) {
- // Write the exception message
- out.println("
Error:
");
- out.println("
"
);
- out.println(e.getMessage());
- out.println("");
- } finally {
- out.close();
- }
- }
- }
纯Servlet上传文件,不用Apache的FileUpload。不过使用的时候建议使用FileUpload组件,有现成的为什么不用呢?
阅读(1660) | 评论(0) | 转发(0) |