Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.86 KB | None | 0 0
  1. /**
  2.   UploadServer program - simple file upload web-server
  3.   Author: Denis Volkov (c) 2007
  4.   For information and support visit http://www.denvo.ru
  5.  
  6.   This program is FREEWARE, you are free to use any part of code
  7.   as well as whole program in your development provided that you
  8.   remain original copyrights and site name in your source.
  9.  
  10.   The product is distributed "as is". The author of the Product will
  11.   not be liable for any consequences, loss of profit or any other kind
  12.   of loss, that may occur while using the product itself and/or together
  13.   with any other software.
  14. */  
  15.  
  16. import java.net.*;
  17. import java.io.*;
  18. import java.security.*;
  19. import java.util.*;
  20. import java.util.regex.*;
  21. import java.nio.charset.*;
  22.  
  23. public class UploadServer extends Thread
  24. {
  25.   private final static String httpHeader = "HTTP/1.1 200 OK\r\n"
  26.     + "Content-Type: text/html\r\n"
  27.     + "\r\n";
  28.   private final static String uploadFormString = httpHeader
  29.     + "<form method=\"POST\" enctype=\"multipart/form-data\">\r\n"
  30.     + "<input type=\"file\" name=\"upload_file\" size=100>\r\n"
  31.     + "<input type=\"submit\" value=\"Upload\">\r\n"
  32.     + "</form>\r\n\r\n";
  33.  
  34.   private final Charset streamCharset = Charset.forName("ISO-8859-1");
  35.  
  36.   private ServerSocket serverSocket;
  37.   private Socket clientSocket;
  38.  
  39.   UploadServer(int port) throws Exception
  40.   {
  41.     serverSocket = new ServerSocket(port);
  42.     System.err.println("Server ready @" + port);
  43.   }
  44.  
  45.   public void run()
  46.   {
  47.     while(true)
  48.     {
  49.       try
  50.       {
  51.         clientSocket = serverSocket.accept();
  52.         System.err.println("Client connection accepted from "
  53.           + clientSocket.getInetAddress().toString());
  54.         // Read and process data from socket
  55.         processConnection();
  56.       }
  57.       catch(Exception e)
  58.       {
  59.         System.err.println("Exception in run's main loop");
  60.         e.printStackTrace();
  61.       }
  62.       // Close socket
  63.       try
  64.       {
  65.         clientSocket.close();
  66.       }
  67.       catch(Exception e) { }
  68.       System.err.println("Client connection closed");
  69.     }
  70.   }
  71.  
  72.   private void processConnection() throws Exception
  73.   {
  74.     InputStream inStream = clientSocket.getInputStream();
  75.     BufferedReader in = new BufferedReader(new InputStreamReader(inStream, streamCharset));
  76.     OutputStream out = clientSocket.getOutputStream();
  77.     // Read requiest header
  78.     String headerLine, firstLine = null;
  79.     Map headerData = new TreeMap();
  80.     Pattern headerPattern = Pattern.compile("([^\\:]+)\\:(.*)");
  81.     while((headerLine = in.readLine()).length() > 0)
  82.     {
  83.       if(firstLine == null)
  84.         firstLine = headerLine;
  85.       else
  86.       {
  87.         Matcher m = headerPattern.matcher(headerLine);
  88.         if(m.matches())
  89.         {
  90.           headerData.put(m.group(1).trim(), m.group(2).trim());
  91.         }
  92.       }
  93.       System.out.println("HEADER: " + headerLine);
  94.     }
  95.     // Process first line of request
  96.     if(firstLine.startsWith("GET"))
  97.     {
  98.       System.out.println("Send upload form");
  99.       // Show upload form
  100.       out.write(uploadFormString.getBytes());
  101.     }
  102.     else if(firstLine.startsWith("POST"))
  103.     {
  104.       // Get body info
  105.       int contentLength = Integer.parseInt((String)(headerData.get("Content-Length")));
  106.       String contentType = (String)(headerData.get("Content-Type"));
  107.       String boundary = "\r\n--" + contentType.substring(contentType.indexOf("boundary=") + 9) + "--";
  108.       System.out.println("File upload, reading body: " + contentLength + " bytes");
  109.       // Prepare to reading
  110.       Pattern fileNamePattern = Pattern.compile("filename=\"([^\"]+)\"");
  111.       OutputStreamWriter writer = null;
  112.       MessageDigest digestMD5 = MessageDigest.getInstance("MD5");
  113.       String fileName = null;
  114.       String prevBuffer = "";
  115.       char[] buffer = new char[16 << 10];
  116.       int totalLength = contentLength;
  117.       // Reading loop
  118.       while(contentLength > 0)
  119.       {
  120.         if(writer == null)
  121.         {
  122.           // Read strings
  123.           String bodyLine = in.readLine();
  124.           contentLength -= bodyLine.length() + 2;
  125.           // Find name of file  
  126.           if(bodyLine.length() > 0)
  127.           {
  128.             Matcher m = fileNamePattern.matcher(bodyLine);
  129.             if(m.find())
  130.             {
  131.               fileName = m.group(1);
  132.             }
  133.           }
  134.           else if(fileName != null)
  135.           {
  136.             OutputStream stream = new FileOutputStream(fileName);
  137.             if(digestMD5 != null)
  138.               stream = new DigestOutputStream(stream, digestMD5);
  139.             writer = new OutputStreamWriter(stream, streamCharset);
  140.           }
  141.           else
  142.             throw new RuntimeException("Name of uploaded file not found");
  143.         }
  144.         else
  145.         {
  146.           // Read data from stream
  147.           int readLength = Math.min(contentLength, buffer.length);
  148.           readLength = in.read(buffer, 0, readLength);
  149.           if(readLength < 0)
  150.             break;
  151.           contentLength -= readLength;
  152.           // Find boundary string
  153.           String curBuffer = new String(buffer, 0, readLength);
  154.           String bothBuffers = prevBuffer + curBuffer;
  155.           int boundaryPos = bothBuffers.indexOf(boundary);
  156.           if(boundaryPos == -1)
  157.           {
  158.             writer.write(prevBuffer, 0, prevBuffer.length());
  159.             prevBuffer = curBuffer;
  160.           }
  161.           else
  162.           {
  163.             writer.write(bothBuffers, 0, boundaryPos);
  164.             break;
  165.           }
  166.         }
  167.         // Write stats
  168.         System.out.print("Read: " + (totalLength - contentLength)
  169.           + " Remains: " + contentLength + " Total: " + totalLength
  170.           + " bytes       \r");
  171.       }
  172.       System.out.println("Done                                                 ");
  173.       writer.close();
  174.       // Finalize digest calculation
  175.       byte[] md5Sum = digestMD5.digest();
  176.       StringBuffer md5SumString = new StringBuffer();
  177.       for(int n = 0; n < md5Sum.length; ++ n)
  178.         md5SumString.append(printByte(md5Sum[n]));
  179.       // Output client info
  180.       String answer = httpHeader + "<p><b>Upload completed, " + totalLength
  181.         + " bytes, MD5 sum: " + md5SumString.toString() + "</b>"
  182.         + "<p><a href=\"/\">Next file</a>\r\n\r\n";
  183.       out.write(answer.getBytes());
  184.     }
  185.   }
  186.  
  187.   private static String printByte(byte b)
  188.   {
  189.     int bi = ((int)b) & 0xFF;
  190.     if(bi < 16)
  191.       return "0" + Integer.toHexString(bi);
  192.     else
  193.       return Integer.toHexString(bi);
  194.   }
  195.  
  196.   public static void main(String[] args)
  197.   {
  198.     try
  199.     {
  200.       if(args.length < 1)
  201.       {
  202.         System.out.println("Usage: UploadServer <port>");
  203.         return;
  204.       }
  205.       UploadServer server = new UploadServer(Integer.parseInt(args[0]));
  206.       server.start();
  207.     }
  208.     catch(Exception e)
  209.     {
  210.       System.err.println("Error in main");
  211.       e.printStackTrace();
  212.     }
  213.   }
  214. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement