歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Android拍照上傳程序的Servlet程序樣例

相關閱讀:Android拍照上傳代碼樣例 http://www.linuxidc.com/Linux/2011-11/47617.htm

UploadFileServlet.java

  1. package com.hemi.rhet.servlet;  
  2.   
  3. import java.io.*;  
  4. import java.net.InetAddress;  
  5. import java.net.UnknownHostException;  
  6. import java.sql.SQLException;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.*;  
  9.   
  10. import javax.servlet.*;  
  11. import javax.servlet.http.*;  
  12.   
  13. //import org.apache.commons.fileupload.*;   
  14. //import org.apache.commons.fileupload.disk.DiskFileItemFactory;   
  15. //import org.apache.commons.fileupload.servlet.ServletFileUpload;   
  16. //import org.apache.commons.lang.time.DateUtils;   
  17. import org.apache.log4j.Logger;  
  18. //import org.apache.struts2.ServletActionContext;   
  19.   
  20.   
  21. public class UploadFileServlet extends HttpServlet  
  22. {  
  23.   
  24.     private static Logger log = Logger.getLogger(UploadFileServlet.class);  
  25.   
  26.     private static final String OBLIQUE_LINE = "/";  
  27.   
  28.     private static final String OPPOSITE_OBLIQUE_LINE = "////";  
  29.   
  30.     private static final String WEBPOSITION = "webapps";  
  31.       
  32.     private static final String SBPATH = "UploadedFiles/";  
  33.   
  34.     File outdir = null;  
  35.   
  36.     File outfile = null;  
  37.   
  38.     FileOutputStream fos = null;  
  39.   
  40.     BufferedInputStream bis = null;  
  41.   
  42.     byte[] bs = new byte[1024];  
  43.   
  44.     String uploadFName = null;  
  45.     String orderNo = null;  
  46.     String userId = null;  
  47.     String attachType = "2";  
  48.   
  49.     public void init() throws ServletException  
  50.     {  
  51. //        if (log.isDebugEnabled())   
  52. //        {   
  53. //            log.debug("進入init()方法!!");   
  54. //        }   
  55.     }  
  56.   
  57.     public void doGet(HttpServletRequest request , HttpServletResponse response) throws IOException, ServletException  
  58.     {  
  59.         doPost(request, response);  
  60.     }  
  61.   
  62.     public void doPost(HttpServletRequest request , HttpServletResponse response) throws IOException, ServletException  
  63.     {  
  64.         String root = this.getServletContext().getRealPath("/");   
  65.         root = root.replaceAll("////""/");  
  66.           
  67.         try  
  68.         {  
  69.             StringBuffer destFName = new StringBuffer();  
  70.             destFName.append(getRealDir(root)).append(SBPATH);  
  71.             outdir = new File(destFName.toString());  
  72.               
  73.             request.setCharacterEncoding("UTF-8");  
  74.               
  75.             uploadFName = request.getParameter("filename");  //name of uploaded file   
  76.             uploadFName = request.getHeader("filename");  
  77.             if (isEmpty(uploadFName)) uploadFName = "filename.jpg";  
  78.             //orderNo = request.getParameter("orderno");       //id of the order or work sheet    
  79.             //userId  = request.getParameter("userid");        //id of the user who upload the file   
  80.             //attachType = request.getParameter("attach_type"); //type of attachment, refer to file.FileBean's definition    
  81.               
  82.             String desc = request.getParameter("desc");      //description of uploaded file   
  83.             if (desc==null) desc = "";  
  84.               
  85.             if (true)  
  86.             {  
  87.                 destFName.append(getDatedFName(uploadFName));  
  88.                 outfile = new File(destFName.toString());  
  89.                   
  90.                 bis = new BufferedInputStream(request.getInputStream());  
  91.                 uploadFile();   
  92.                   
  93.                 //response.getWriter().write("0");  //success   
  94.                 response.setHeader("resultcode""0");  
  95.   
  96.             }  
  97.             else if (desc.length() > 400/2) {  
  98.                 //response.getWriter().write("3");  //illegal description   
  99.                 response.setHeader("resultcode""3");  
  100.             }  
  101.             else  
  102.             {  
  103.                 if (log.isDebugEnabled())  
  104.                 {  
  105.                     log.debug("調用格式錯誤!");  
  106.                 }  
  107.                 response.sendError(100"參數錯誤!");  
  108.                 //response.getWriter().write("1");   
  109.                 response.setHeader("resultcode""1");  //parameter error   
  110.                   
  111.                 //return;   
  112.             }  
  113.         } catch (SQLException e) {  
  114.             if (log.isDebugEnabled()) {  
  115.                 log.debug(e);  
  116.             }  
  117.               
  118.             //response.getWriter().write("6");  //failure of insert to database    
  119.             response.setHeader("resultcode""6");  
  120.   
  121.         } catch (Exception e) {  
  122.             if (log.isDebugEnabled()) {  
  123.                 log.debug(e);  
  124.             }  
  125.             //response.getWriter().write("7");  //failure   
  126.             response.setHeader("resultcode""7");  
  127.               
  128.         } finally {  
  129.             if (null != bis)  
  130.                 bis.close();  
  131.             if (null != fos)  
  132.                 fos.close();  
  133.         }  
  134.     }  
  135.   
  136.     private void uploadFile() throws IOException  
  137.     {  
  138.         if (log.isDebugEnabled())  
  139.         {  
  140.             log.debug("outdir:" + outdir.getPath());  
  141.             log.debug("outfile:" + outfile.getPath());  
  142.         }  
  143.         if (!outdir.exists())  
  144.             outdir.mkdir();  
  145.         if (!outfile.exists())  
  146.             outfile.createNewFile();  
  147.   
  148.         fos = new FileOutputStream(outfile);  
  149.         int i;  
  150.         while ((i = bis.read(bs)) != -1)  
  151.         {  
  152.             fos.write(bs, 0, i);  
  153.         }  
  154.     }  
  155.       
  156.     public static String getDatedFName(String fname) {  
  157.         StringBuffer result = new StringBuffer();  
  158.   
  159.         SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");  
  160.         String dateSfx = "_" + df.format(new Date());  
  161.   
  162.         int idx = fname.lastIndexOf('.');  
  163.         if (idx != -1) {  
  164.             result.append(fname.substring(0, idx));  
  165.             result.append(dateSfx);  
  166.             result.append(fname.substring(idx));  
  167.         } else {  
  168.             result.append(fname);  
  169.             result.append(dateSfx);  
  170.         }  
  171.   
  172.         return result.toString();  
  173.     }  
  174.       
  175.     public static String getUrlFName(String fname, HttpServletRequest request) {  
  176.         String result = "";   
  177.         if (isEmpty(fname)) return result;  
  178.           
  179.         try {  
  180.             if (fname.startsWith("http://")) {  
  181.                 result = fname;  
  182.             } else {  
  183.                 //HttpServletRequest request = ServletActionContext.getServletContext().getRgetRequest();   
  184.                 //UserAndOrganAndRole user = (UserAndOrganAndRole)request.getSession().getAttribute("user");   
  185.                   
  186.                 String ip = request.getServerName();  
  187.                 int port = request.getServerPort();  
  188.                   
  189.                 result = fname.substring(fname.indexOf(UploadFileServlet.SBPATH));  
  190.                 StringBuffer tmpBuff = new StringBuffer();  
  191.                 tmpBuff.append("http://").append(ip).append(":").append(port).append(OBLIQUE_LINE).append(result);  
  192.                 //Sample: http://localhost:8083/UploadedFiles/IMAGE_067_100222102521.jpg   
  193.   
  194.                 result = tmpBuff.toString();  
  195.   
  196.             }  
  197.         } catch (Exception ex) {  
  198.             ex.printStackTrace();  
  199.         }  
  200.           
  201.         System.out.println("result is: "+result);  
  202.         return result;    
  203.     }  
  204.       
  205.     public static boolean isEmpty(String str) {  
  206.         return ((str == null) || (str.length() == 0));  
  207.     }  
  208.   
  209.     /** 
  210.      * Method getRealDir search webapps position 
  211.      *  
  212.      * @param despath 
  213.      *  
  214.      * @return 
  215.      *  
  216.      */  
  217.     private String getRealDir(String newFileNameRoot) throws Exception {  
  218.         if (newFileNameRoot == null)  
  219.             throw new Exception("get real dir failed !");  
  220.         int dp = newFileNameRoot  
  221.                 .lastIndexOf(OBLIQUE_LINE);  
  222.         if (dp == -1)  
  223.             throw new Exception("invalid path !");  
  224.         int dpbefore = newFileNameRoot.lastIndexOf(  
  225.                 OBLIQUE_LINE, dp - 1);  
  226.         if (dpbefore == -1)  
  227.             throw new Exception("invalid path !");  
  228.         String needSubStr = newFileNameRoot.substring(dpbefore + 1, dp);  
  229.         String nextStr = newFileNameRoot.substring(0, dpbefore + 1);  
  230.         if (!needSubStr.trim().equals(WEBPOSITION)) {  
  231.             return getRealDir(nextStr);  
  232.   
  233.         } else  
  234.             return newFileNameRoot;  
  235.     }  
  236.       
  237.     public static void main(String[] args)  
  238.     {  
  239.   
  240.     }  
  241. }  

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4"   
  3.     xmlns="http://java.sun.com/xml/ns/j2ee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  7.   <welcome-file-list>  
  8.     <welcome-file>index.jsp</welcome-file>  
  9.   </welcome-file-list>  
  10.     
  11.   <servlet>      
  12.         <servlet-name>Upload</servlet-name>      
  13.         <servlet-class>com.hemi.rhet.servlet.UploadFileServlet</servlet-class>      
  14.     </servlet>         
  15.     <servlet-mapping>      
  16.         <servlet-name>Upload</servlet-name>      
  17.         <url-pattern>/system/fileUpload</url-pattern>      
  18.     </servlet-mapping>  
  19. </web-app>  
Copyright © Linux教程網 All Rights Reserved