相關閱讀:Android拍照上傳代碼樣例 http://www.linuxidc.com/Linux/2011-11/47617.htm
UploadFileServlet.java
- package com.hemi.rhet.servlet;
-
- import java.io.*;
- import java.net.InetAddress;
- import java.net.UnknownHostException;
- import java.sql.SQLException;
- import java.text.SimpleDateFormat;
- import java.util.*;
-
- import javax.servlet.*;
- import javax.servlet.http.*;
-
- //import org.apache.commons.fileupload.*;
- //import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- //import org.apache.commons.fileupload.servlet.ServletFileUpload;
- //import org.apache.commons.lang.time.DateUtils;
- import org.apache.log4j.Logger;
- //import org.apache.struts2.ServletActionContext;
-
-
- public class UploadFileServlet extends HttpServlet
- {
-
- private static Logger log = Logger.getLogger(UploadFileServlet.class);
-
- private static final String OBLIQUE_LINE = "/";
-
- private static final String OPPOSITE_OBLIQUE_LINE = "////";
-
- private static final String WEBPOSITION = "webapps";
-
- private static final String SBPATH = "UploadedFiles/";
-
- File outdir = null;
-
- File outfile = null;
-
- FileOutputStream fos = null;
-
- BufferedInputStream bis = null;
-
- byte[] bs = new byte[1024];
-
- String uploadFName = null;
- String orderNo = null;
- String userId = null;
- String attachType = "2";
-
- public void init() throws ServletException
- {
- // if (log.isDebugEnabled())
- // {
- // log.debug("進入init()方法!!");
- // }
- }
-
- public void doGet(HttpServletRequest request , HttpServletResponse response) throws IOException, ServletException
- {
- doPost(request, response);
- }
-
- public void doPost(HttpServletRequest request , HttpServletResponse response) throws IOException, ServletException
- {
- String root = this.getServletContext().getRealPath("/");
- root = root.replaceAll("////", "/");
-
- try
- {
- StringBuffer destFName = new StringBuffer();
- destFName.append(getRealDir(root)).append(SBPATH);
- outdir = new File(destFName.toString());
-
- request.setCharacterEncoding("UTF-8");
-
- uploadFName = request.getParameter("filename"); //name of uploaded file
- uploadFName = request.getHeader("filename");
- if (isEmpty(uploadFName)) uploadFName = "filename.jpg";
- //orderNo = request.getParameter("orderno"); //id of the order or work sheet
- //userId = request.getParameter("userid"); //id of the user who upload the file
- //attachType = request.getParameter("attach_type"); //type of attachment, refer to file.FileBean's definition
-
- String desc = request.getParameter("desc"); //description of uploaded file
- if (desc==null) desc = "";
-
- if (true)
- {
- destFName.append(getDatedFName(uploadFName));
- outfile = new File(destFName.toString());
-
- bis = new BufferedInputStream(request.getInputStream());
- uploadFile();
-
- //response.getWriter().write("0"); //success
- response.setHeader("resultcode", "0");
-
- }
- else if (desc.length() > 400/2) {
- //response.getWriter().write("3"); //illegal description
- response.setHeader("resultcode", "3");
- }
- else
- {
- if (log.isDebugEnabled())
- {
- log.debug("調用格式錯誤!");
- }
- response.sendError(100, "參數錯誤!");
- //response.getWriter().write("1");
- response.setHeader("resultcode", "1"); //parameter error
-
- //return;
- }
- } catch (SQLException e) {
- if (log.isDebugEnabled()) {
- log.debug(e);
- }
-
- //response.getWriter().write("6"); //failure of insert to database
- response.setHeader("resultcode", "6");
-
- } catch (Exception e) {
- if (log.isDebugEnabled()) {
- log.debug(e);
- }
- //response.getWriter().write("7"); //failure
- response.setHeader("resultcode", "7");
-
- } finally {
- if (null != bis)
- bis.close();
- if (null != fos)
- fos.close();
- }
- }
-
- private void uploadFile() throws IOException
- {
- if (log.isDebugEnabled())
- {
- log.debug("outdir:" + outdir.getPath());
- log.debug("outfile:" + outfile.getPath());
- }
- if (!outdir.exists())
- outdir.mkdir();
- if (!outfile.exists())
- outfile.createNewFile();
-
- fos = new FileOutputStream(outfile);
- int i;
- while ((i = bis.read(bs)) != -1)
- {
- fos.write(bs, 0, i);
- }
- }
-
- public static String getDatedFName(String fname) {
- StringBuffer result = new StringBuffer();
-
- SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
- String dateSfx = "_" + df.format(new Date());
-
- int idx = fname.lastIndexOf('.');
- if (idx != -1) {
- result.append(fname.substring(0, idx));
- result.append(dateSfx);
- result.append(fname.substring(idx));
- } else {
- result.append(fname);
- result.append(dateSfx);
- }
-
- return result.toString();
- }
-
- public static String getUrlFName(String fname, HttpServletRequest request) {
- String result = "";
- if (isEmpty(fname)) return result;
-
- try {
- if (fname.startsWith("http://")) {
- result = fname;
- } else {
- //HttpServletRequest request = ServletActionContext.getServletContext().getRgetRequest();
- //UserAndOrganAndRole user = (UserAndOrganAndRole)request.getSession().getAttribute("user");
-
- String ip = request.getServerName();
- int port = request.getServerPort();
-
- result = fname.substring(fname.indexOf(UploadFileServlet.SBPATH));
- StringBuffer tmpBuff = new StringBuffer();
- tmpBuff.append("http://").append(ip).append(":").append(port).append(OBLIQUE_LINE).append(result);
- //Sample: http://localhost:8083/UploadedFiles/IMAGE_067_100222102521.jpg
-
- result = tmpBuff.toString();
-
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- }
-
- System.out.println("result is: "+result);
- return result;
- }
-
- public static boolean isEmpty(String str) {
- return ((str == null) || (str.length() == 0));
- }
-
- /**
- * Method getRealDir search webapps position
- *
- * @param despath
- *
- * @return
- *
- */
- private String getRealDir(String newFileNameRoot) throws Exception {
- if (newFileNameRoot == null)
- throw new Exception("get real dir failed !");
- int dp = newFileNameRoot
- .lastIndexOf(OBLIQUE_LINE);
- if (dp == -1)
- throw new Exception("invalid path !");
- int dpbefore = newFileNameRoot.lastIndexOf(
- OBLIQUE_LINE, dp - 1);
- if (dpbefore == -1)
- throw new Exception("invalid path !");
- String needSubStr = newFileNameRoot.substring(dpbefore + 1, dp);
- String nextStr = newFileNameRoot.substring(0, dpbefore + 1);
- if (!needSubStr.trim().equals(WEBPOSITION)) {
- return getRealDir(nextStr);
-
- } else
- return newFileNameRoot;
- }
-
- public static void main(String[] args)
- {
-
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4"
- xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
-
- <servlet>
- <servlet-name>Upload</servlet-name>
- <servlet-class>com.hemi.rhet.servlet.UploadFileServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>Upload</servlet-name>
- <url-pattern>/system/fileUpload</url-pattern>
- </servlet-mapping>
- </web-app>