歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android拍照上傳程序的Servlet程序樣例

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

日期:2017/3/1 10:57:39   编辑:Linux編程

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

UploadFileServlet.java

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

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. <servlet>
  11. <servlet-name>Upload</servlet-name>
  12. <servlet-class>com.hemi.rhet.servlet.UploadFileServlet</servlet-class>
  13. </servlet>
  14. <servlet-mapping>
  15. <servlet-name>Upload</servlet-name>
  16. <url-pattern>/system/fileUpload</url-pattern>
  17. </servlet-mapping>
  18. </web-app>
Copyright © Linux教程網 All Rights Reserved